This repository has been archived by the owner on Sep 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
correcoef.hhs
79 lines (66 loc) · 2.54 KB
/
correcoef.hhs
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* @Author Jianan Lin (林家南)
* @param A an array / matrix / tensor
* @param B an array / matrix / tensor
* @returns - a number = correlation coefficient of A and B
* up to now only support one dimension correlatioin coefficient
* need to add support for matrix calculation after some work
*
*/
function correcoef(A, B) {
*import math: ndim
*import math: deep_copy
*import math: flatten
if (arguments.length === 0) {
throw new Error('Exception occurred in correcoef - no argument given');
}
if (arguments.length > 2) {
throw new Error('Exception occurred in correcoef - no argument given');
}
if (!(Array.isArray(A)) && !(A instanceof Mat) && !(A instanceof Tensor)) {
throw new Error('Exception occurred in correcoef - A must be an array, matrix or tensor');
}
if (!(Array.isArray(B)) && !(B instanceof Mat) && !(B instanceof Tensor)) {
throw new Error('Exception occurred in correcoef - A must be an array, matrix or tensor');
}
let in_type_A = (A instanceof Mat) || (A instanceof Tensor);
let raw_in_A = in_type_A ? A.clone().val : deep_copy(A);
if (ndim(raw_in_A) > 1) {
raw_in_A = flatten(raw_in_A);
}
if (raw_in_A.length === 0) {
throw new Error('Exception occurred in correcoef - A cannot be empty');
// return[0]
}
let in_type_B = (B instanceof Mat) || (B instanceof Tensor);
let raw_in_B = in_type_B ? B.clone().val : deep_copy(B);
if (ndim(raw_in_B) > 1) {
raw_in_B = flatten(raw_in_B);
}
if (raw_in_B.length === 0) {
throw new Error('Exception occurred in correcoef - B cannot be empty');
// return[0]
}
if (raw_in_A.length !== raw_in_B.length) {
throw new Error('Exception occurred in correcoef - A and B must have the same length');
}
let sumA = 0;
for (let i = 0; i < raw_in_A.length; i++) {
sumA = sumA + raw_in_A[i];
}
let meanA = sumA / raw_in_A.length;
let sumB = 0;
for (let i = 0; i < raw_in_B.length; i++) {
sumB = sumB + raw_in_B[i];
}
let meanB = sumA / raw_in_B.length;
let result1 = 0, result2 = 0, result3 = 0;
for (let i = 0; i < raw_in_A.length; i++) {
result1 = result1 + (raw_in_A[i] - meanA) * (raw_in_B[i] - meanB);
result2 = result2 + (raw_in_A[i] - meanA) * (raw_in_A[i] - meanA);
result3 = result3 + (raw_in_B[i] - meanB) * (raw_in_B[i] - meanB);
}
result2 = mathjs.sqrt(result2);
result3 = mathjs.sqrt(result3);
return result1 / result2 / result3;
}