Convention with rows and columns index for most of languages

802 views Asked by At

Following the question on this link, Is it a general rule (I mean for a majority of languages) to consider, for a 2 dimensional array "x(i,j)", the first index i for the index of rows and index j for the index of columns ?

I know that Fortran is column major, C Language is row major, and for both, it seems that classical convention is i = rows and j = columns, doesn't it ?

Moreover, could anyone tell me if Matlab is row or column major ?

3

There are 3 answers

0
Lundin On BEST ANSWER

This is a misunderstanding. There is no relation between how raw data is allocated in memory and the higher-level representation that the raw data is supposed to model.

C does not place any meaning to the indices in [i][j], this just specifies how the data is allocated in memory, not how it is presented to a user. i could be rows or it could be columns, this is for the programmer to specify in their application.

However, C does allocate the right-most dimension together in memory, example:

int arr[2][3] = { {1,2,3}, {1,2,3} };

+-------+-------+-------+-------+-------+-------+
|       |       |       |       |       |       |
|   1   |   2   |   3   |   1   |   2   |   3   |
|       |       |       |       |       |       |
+-------+-------+-------+-------+-------+-------+

This means that the preferred way to iterate over this matrix is:

for(size_t i=0; i<2; i++)
  for(size_t j=0; j<3; j++)
    arr[i][j] = x;

Because this order gives the fastest memory access, as far as cache memory is concerned. But the language does not enforce this order, we can iterate with j in the outer loop and the program will work just as fine (just slower).

Nor can we tell if this matrix is supposed to be a 2x3 or a 3x2.

1
schorsch312 On

Your question is answered here.

Quote:

In summary:

The "shape" of the memory is exactly the same in C and Fortran even though language differences make it look different due to reversed array indexing.

If you don't iterate through a Fortran array in k,j,i order, you'll access memory out of order and negatively impact your cache performance.

3
Sam Roberts On

For MATLAB, the first index is the row and the second is the column. But arrays are stored internally in column-major order (very early versions of MATLAB were implemented in FORTRAN; when it was originally commercialised it was mostly converted into C, but kept that convention).