skip to Main Content

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.

2

Answers


  1. 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];
        }
      }
    }
    
    Login or Signup to reply.
  2. You’ll need to sum the total offset at each loop iteration. Here’s a reproducible example — based on the code in your question — with parametrized variables and comments explaining the logic:

    /** @type {number[][][]} */
    const matrix = [
      [
        [1,  2,  3,  4],
        [5,  6,  7,  8],
        [9, 10, 11, 12],
      ],
      [
        [13, 14, 15, 16],
        [17, 18, 19, 20],
        [21, 22, 23, 24],
      ],
    ];
    
    /** @type {number[]} */
    const flat = [];
    
    const a = matrix.length; // 2
    const b = matrix[0].length; // 3
    const c = matrix[0][0].length; // 4
    
    for (let ia = 0; ia < a; ia++) {
      for (let ib = 0; ib < b; ib++) {
        for (let ic = 0; ic < c; ic++) {
          const index =
              ic // offset from inner loop
            + (c * ib) // offset from middle loop
            + (c * b * ia); // offset from outer loop
          flat[index] = matrix[ia][ib][ic];
        }
      }
    }
    
    console.log(flat); // [1, 2, … 23, 24]
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search