将线性阵列转换为矩阵的有效方法

时间:2016-11-11 13:01:09

标签: javascript arrays matrix

我有一个数组,其中包含一个带有x坐标,y坐标和矩阵值的子阵列:

// [x,y,value]
var arr = [
[1,2,0.01],
[1,3,0.02],
[1,4,0.05],
[1,5,0.03],
[2,3,0.04],
[2,4,0.02],
[2,5,0.01],
[3,4,0.06],
[3,5,0.05],
[4,5,0.07],
]

然后我有一个零填充的二维数组("矩阵")x_max X x_max维。我尝试使用计算效率高的方法来填充此矩阵的值,如下所示:

// already have a variable called 'matrix' which is zero-filled

function constructMatrix(){
    for(var i in arr){
        var y = arr[i][0];
        var x = arr[i][1];
        var val = arr[i][2];
        matrix[y][x] = val;
    }
}

我得到的是一个矩阵,它具有唯一的列值,但跨行的值相同。我的逻辑在某处有一个简单的中断吗?

我希望输出如下:

var matrix = [
[0.01,0.02,0.05,0.03],
[0,0.04,0.02,0.01],
[0,0,0.06,0.05],
[0,0,0,0.07],
]

2 个答案:

答案 0 :(得分:2)

你可以这样做:



/

var arr = [
    [1, 2, 0.01], [1, 3, 0.02], [1, 4, 0.05], [1, 5, 0.03],
    [2, 3, 0.04], [2, 4, 0.02], [2, 5, 0.01], [3, 4, 0.06],
    [3, 5, 0.05], [4, 5, 0.07]
];

// find total number of rows and columns
// add 1 because (x = 5) == (index 6)    // indexes start at 0
var rows = arr.reduce((x,y) => Math.max(x, y[0]), 0) + 1;
var columns = arr.reduce((x,y) => Math.max(x, y[1]), 0) + 1;

// initiate an empty matrix 
var matrix = [...Array(rows)].map(() => Array(columns).fill(0));

// loop over the points
arr.forEach(function(point) {
    var x = point[0];
    var y = point[1];
    var val = point[2];
    matrix[x][y] = val;
});

// your result
console.log(  JSON.stringify(matrix, 0, 2)  );




答案 1 :(得分:1)

如果坐标(1,2)表示第一列,第二行则应该

matrix[y - 1][x - 1] = val

因为坐标从0,0开始并在4,4(对于5x5矩阵)完成