Below is the code snippet
const arrayColumn = (arr, n) => arr.map(x => x[n]);
const pcorr = (x, y) => {
let sumX = 0,
sumY = 0,
sumXY = 0,
sumX2 = 0,
sumY2 = 0;
const minLength = x.length = y.length = Math.min(x.length, y.length),
reduce = (xi, idx) => {
const yi = y[idx];
sumX += xi;
sumY += yi;
sumXY += xi * yi;
sumX2 += xi * xi;
sumY2 += yi * yi;
}
x.forEach(reduce);
return (minLength * sumXY - sumX * sumY) / Math.sqrt((minLength * sumX2 - sumX * sumX) * (minLength * sumY2 - sumY * sumY));
};
// Generating a Pearson correlation matrix
var r = [[]];
var r_temp = [];
for (var i = 1; i <= _arrData[0].length; i++) {
for (var j = 1; j <= _arrData[0].length; j++) {
r_temp.push(pcorr(arrayColumn(_arrData,i-1),arrayColumn(_arrData,j-1)));
}
}
var r_temp_length = r_temp.length;
for (var i = 1; i <= _arrData[0].length; i++) {
for (var j = 1; j <= _arrData[0].length; j++) {
r[i - 1][j - 1] = r_temp[_arrData[0].length^2 - r_temp_length];
r_temp_length = r_temp_length - 1;
}
}
_arrData represents data from a .csv file that has been read and formatted as a 43x4 matrix. The result of r_temp is shown below:
[1, 0.1001546791334383, -0.09722360940329312, -0.1119017933192886, 0.1001546791334383, 1, 0.19766088533723247, -0.03844791092325515, -0.09722360940329312, 0.19766088533723247, 1, -0.06161560854254137, -0.1119017933192886, -0.03844791092325515, -0.06161560854254137, 1]
The length of r_temp is 16.
The aim is to input the values from r_temp into r, creating a 4x4 Matrix.
An error occurs at this specific line when running the code:
r[i - 1][j - 1] = r_temp[_arrData[0].length^2 - r_temp_length];
The following error message is displayed: Uncaught TypeError: Cannot set property '0' of undefined.