covarianceMatrix method

Matrix covarianceMatrix()

Returns the covariance matrix of the input matrix.

Throws an exception if the matrix is empty.

Example:

var matrix = Matrix([[1, 2], [3, 4], [5, 6]]);
print(matrix.covarianceMatrix());
// Output:
// 4.0 4.0
// 4.0 4.0

Implementation

Matrix covarianceMatrix() {
  if (rowCount == 0) {
    throw Exception("Matrix is empty");
  }

  int dimensions = columnCount;
  int n = rowCount;

  List<List<dynamic>> means = [];
  for (int j = 0; j < dimensions; j++) {
    dynamic sum = Complex.zero();
    for (int i = 0; i < n; i++) {
      sum += _data[i][j];
    }
    means.add(List.filled(n, Complex(sum / n)));
  }

  List<List<dynamic>> centeredData = [];
  for (int i = 0; i < n; i++) {
    List<dynamic> row = [];
    for (int j = 0; j < dimensions; j++) {
      row.add(_data[i][j] - means[j][i]);
    }
    centeredData.add(row);
  }

  List<List<dynamic>> covMatrix = List.generate(
      dimensions, (_) => List<Complex>.filled(dimensions, Complex.zero()));

  for (int i = 0; i < dimensions; i++) {
    for (int j = 0; j < dimensions; j++) {
      dynamic sum = Complex.zero();
      for (int k = 0; k < n; k++) {
        sum += centeredData[k][i] * centeredData[k][j];
      }
      covMatrix[i][j] = sum / Complex(n - 1);
    }
  }

  return Matrix(covMatrix);
}