Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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];
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading