javascriptloopsmatrixindexingflatten

Matrix indexing/flattening


I am given a matrix with dimensions dim = nxmx4. I would like to flatten this matrix to a new 1-dimensional matrix with length l = n*m*4 using 3 nested for-loops.

for (let x = 0; x < n; x++) {
    for (let y = 0; y < m; y++) {
        for (let i = 0; i < 4; i++) {
            let index = ?;
            newMatrix[index] = matrix[x][y][i];
        }
    }
}

Additionally the condition index % 4 == i should always hold.

To be more precise, the values of matrix[x][y][i] don't matter that much for now (can be arbitrary), as long as the index is increased by one each iteration. For i = 0 -> index = 0, 4, 8, ... should be returned | i = 1 -> index = 1, 5, 9, ... | i = 2 -> index = 2, 6, 10, ... | and i = 3 -> index = 3, 7, 11, ...

I can't come up with the correct indexing right now. Thanks in advance.


Solution

  • You can use index = x * m * 4 + y * 4 + i;:

    let newMatrix = [];
    for (let x = 0; x < n; x++) {
      for (let y = 0; y < m; y++) {
        for (let i = 0; i < 4; i++) {
          let index = x * m * 4 + y * 4 + i;
          newMatrix[index] = matrix[x][y][i];
        }
      }
    }