0

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],
]
5
  • 2
    Could you give us an exemple of expected output ? Commented Nov 11, 2016 at 13:05
  • @kevinternet there you are. Commented Nov 11, 2016 at 13:09
  • Here's a fiddle of the problem: jsfiddle.net/ocwna691 Commented Nov 11, 2016 at 13:15
  • 1
    Could you also add the code for zero-filling the matrix variable ? Commented Nov 11, 2016 at 13:16
  • @KiJéy See the fiddle. I think that will be easier to understand. Commented Nov 11, 2016 at 13:17

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

very elegant! Much better than what I had, plus it works! Thanks.
1

If by the coordinates (1,2) you mean first column, second row then you should do

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

because coordinates start at 0,0 and finish at 4,4 (for a 5x5 matrix)

1 Comment

That's something I need to do, correct, but if I substitute it in the fiddle I still get the same problem (but now with correct coordinates).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.