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

Convert linear index to row, column

I have a 2D array (int[][]) and switch between tracking of position in the matrix between a linear index and coordinates (row, column).

I have a method calculating the linear index from a row and column:

private int linearIndex(int r, int c){
        return (r*columns) + c;
    }

where columns is the nr of columns in the matrix (3×4 matrix -> columns = 4)

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’m having troubles getting the row, column position from the linear index. My current approach is:
row = linear index % rows
column = linear index / columns

Where – once again – rows = total number of rows and columns = total number of columns

See above, issues arise on the first column when on a row > 0…

>Solution :

Your approach for calculating the row and column from the linear index is almost correct. The issue arises because you are using the total number of columns instead of the total number of rows for the row calculation.

Here is one way you can calculate the row and column from the linear index:

int row = linearIndex / columns;
int column = linearIndex % columns;

This approach works because the row is the integer division of the linear index by the number of columns, and the column is the remainder of the integer division of the linear index by the number of columns.

You can also calculate the row and column using the modulo operator instead of integer division, like this:

int row = linearIndex % (rows * columns) / columns;
int column = linearIndex % columns;

This approach works because the modulo operator returns the remainder of the division, and the remainder of the division of the linear index by the total number of cells in the matrix (rows * columns) is the same as the linear index of the cell in the first row. Then, we can calculate the row by taking the integer division of the result by the number of columns, and the column is the same as the result of the modulo operator.

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