-
Notifications
You must be signed in to change notification settings - Fork 0
/
covariance.js
36 lines (34 loc) · 941 Bytes
/
covariance.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { isAnyArray } from './indexIsAnyArray.js';
import Matrix from './matrix.js';
export function covariance(xMatrix, yMatrix = xMatrix, options = {}) {
xMatrix = new Matrix(xMatrix);
let yIsSame = false;
if (
typeof yMatrix === 'object' &&
!Matrix.isMatrix(yMatrix) &&
!isAnyArray(yMatrix)
) {
options = yMatrix;
yMatrix = xMatrix;
yIsSame = true;
} else {
yMatrix = new Matrix(yMatrix);
}
if (xMatrix.rows !== yMatrix.rows) {
throw new TypeError('Both matrices must have the same number of rows');
}
const { center = true } = options;
if (center) {
xMatrix = xMatrix.center('column');
if (!yIsSame) {
yMatrix = yMatrix.center('column');
}
}
const cov = xMatrix.transpose().mmul(yMatrix);
for (let i = 0; i < cov.rows; i++) {
for (let j = 0; j < cov.columns; j++) {
cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1)));
}
}
return cov;
}