-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcorrelation.js
More file actions
53 lines (48 loc) · 1.25 KB
/
correlation.js
File metadata and controls
53 lines (48 loc) · 1.25 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { isAnyArray } from './indexIsAnyArray.js';
import Matrix from './matrix.js';
export function correlation(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, scale = true } = options;
if (center) {
xMatrix.center('column');
if (!yIsSame) {
yMatrix.center('column');
}
}
if (scale) {
xMatrix.scale('column');
if (!yIsSame) {
yMatrix.scale('column');
}
}
const sdx = xMatrix.standardDeviation('column', { unbiased: true });
const sdy = yIsSame
? sdx
: yMatrix.standardDeviation('column', { unbiased: true });
const corr = xMatrix.transpose().mmul(yMatrix);
for (let i = 0; i < corr.rows; i++) {
for (let j = 0; j < corr.columns; j++) {
corr.set(
i,
j,
corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1)),
);
}
}
return corr;
}