Wagtail Wagtail - 21 days ago 7
Javascript Question

Efficient approach for converting linear array to matrix

I have an array containing a subarray with x-coordinates, y-coordinates, and values for a matrix:

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


Then I have a zero-filled 2D array ("matrix") of x_max X x_max dimensions. I'm trying to use a computationally efficient approach to fill in the values of this matrix as follows:

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


What I'm getting is a matrix with unique column values but the same value across rows. Is there a simple break in my logic somewhere?

I would expect output like the following:

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

Answer

You can do this way:

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

Comments