MATLAB: Row/Col major order in mex function

ccolumn major orderlinear indexingmexrow major order

I have a question regarding row/column order in a C Mex-Function.
I am trying to access elements in a matrix contiguously, for speed.
I wrote a mex function in C, which takes a matrix as input:
im1 = mxGetPr(prhs[0]);
Let's say that
im1 = [1 2 3;
4 5 6]
Now, C has row major order, so linear indices are obtained from the row and column coordinates (r,c) as follows:
index = c + nbr_of_col * r;
However, when I print the values with
for( int r = 0; r < nbr_of_row; r++ ){
for( int c = 0; c < nbr_of_col; c++){
mexPrintf("im1[%d][%d] = %0.2f \t", r, c, im1[c + nCol*r]);
}
mexPrintf("\n")
}
I get:
1 4 2
5 3 6
Which shows that it is traversing the matrix columnwise (using the linear indexing convention of Matlab): 1,4,2,5,3,6.
My question is : I can use the indexing formula
index = r + nbr_of_row*c
to traverse the matrix row-wise. Which major order is faster? I thought Row-major was faster since it's in C, but mxGetPr linearizes matrices according to the MATLAB convention…

Best Answer

Other things being equal, the fastest way is to access the data in the order that it is physically stored in memory. This makes the most efficient use of the processor cache system. Bottom line for MATLAB arrays, access them in column order even if you are inside a C mex routine. And I would advise to simply use your own linear indexing formulas for this (as you have shown above) rather than trying to coax a 2D array syntax such as variable[i][j] in your C code.