gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:17:34 24 4
gpt4 key购买 nike

我有一个数组,其中包含一个带有 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],
]

最佳答案

你可以这样做:

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) );
.as-console-wrapper {
max-height: 100%!important;
}

关于javascript - 将线性阵列转换为矩阵的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40548595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com