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 ?
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.