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 25 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