Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Index from row and column

I want to calculate an index (base 0) for any given row and column where rows and columns are base 1 and the number of columns is known, e.g. 2

If max_columns is 2 and index is 5, then to calculate row number from an index:

Row = (index % max_columns) + (int)(index / max_columns)
    = (5 % 2) + (int)(5 / 2)
    = 1 + 2
    = 3

To calculate column number from index

Col = max_columns - (index % max_columns)
    = 2 - (5 % 2)
    = 2 - 1
    = 1

Question is how to calculate row and column from any index where the index is base 0. This is to calculate an index into an array in a java application.

The correct solution for me as supplied by 'Willem Van Onsem':

Where Row is 3, Col is 2 and max_columns is 2:

Index = (Row * max_columns) + Col - max_columns - 1
      = (3 * 2) + 2 - 2 - 1
      = 6 + (-1)
      = 5
like image 625
SPlatten Avatar asked Mar 02 '16 13:03

SPlatten


People also ask

What is the formula to calculate index?

(1) Calculation of indices of items for municipalities Indices of items are calculated by dividing the price in the comparison period by the price in the base period for each municipality.

How do I find row and column index?

For example, if we have a data frame called df that contains a value say Data then we can find the row and column index of Data by using the command as which(df=="Data",arr. ind=TRUE).

What is row index in Matrix?

Description. Returns a matrix of integers indicating their row number in a matrix-like object, or a factor indicating the row labels.

What is index and column?

Create an index column to show the number of a row in a query. This is especially useful when you are filtering by row position or by a range or rows. The index column can help you confirm your results. An index column is also added to an Excel worksheet when you load it.


1 Answers

Given every row consists out of n columns, the zero-based index for the column and row are:

int row = index/n;
int col = index%n;

Now since your row and col are offset 1, you simply add 1 to both:

int row1 = (index/n)+1;
int col1 = (index%n)+1;

For the inverse function, if row and col are offset 0, you can calculate the index as:

int index = row*n+col;

or if the indexes are offset 1:

int index = row1*n+col1-n-1;
like image 129
Willem Van Onsem Avatar answered Sep 24 '22 04:09

Willem Van Onsem