开发者问题收集

如何在 javascript 中将一维数组转换为二维数组

2018-01-12
399

这是我的代码

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));
};

//create 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 是来自 .csv 文件的数据,该文件已读取为矩阵 43X4 r_temp 结果是

[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]

r_temp 长度为 16

我想将 r_temp 值输入到 r 中,它将是 4x4 矩阵

当我运行此代码时,此部分出现错误

r[i - 1][j - 1] = r_temp[_arrData[0].length^2 - r_temp_length];

未捕获的 TypeError:无法设置未定义的属性“0”

2个回答
var r = [];

...

for (var i = 1; i <= _arrData[0].length; i++) {
    r[i - 1] = [];

....

应该是 var r = []; 而不是 [[]]。

您的代码中缺少行 r[i - 1] = [];。

它为 r[i - 1] 创建了第二个数组。

D. Braun
2018-01-12

谢谢大家,它起作用了!

//create pearson correlation matrix
        var r = [];
        for (var i = 1; i <= _arrData[0].length; i++) {
          r[i - 1] = [];
        }
        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[Math.pow(_arrData[0].length,2) - r_temp_length];
            r_temp_length = r_temp_length - 1;
          }
        }
Rendy Eza Putra
2018-01-12