Search code examples
cmatlabmatrixmexmatrix-indexing

Linear indexing of Matlab matrices in MEX file


I have a NxN symmetric matrix F of the following form

F_11 F_12 F_13 ... F_1N 

F_21 ...      

F_31

.
.
.

F_N1 F_N2 F_N3 ... F_NN

with each submatrices F_IJ of size m x m.

This matrix is created in MatLab, and will be used in a C-programm. So the values are stored in a vector columnwise. (E.g the vector will be of the form : (F_11_11,F_11_21,F_11_31,...F_11_m1,F_21_11,...F_NN_(m-1)m,F_NN_mm).

My question is the following: For readability I would like to define in C a way to access the values of F, given the indices (I,J) of the location of the first submatrix, and the indices (i,j) of the location of value in the submatrix. How can I link the linear indexing of the matrix to the (I,J,i,j) indices?


Solution

  • I assume all indices to be zero based, as usual in C/C++. If you want to use Matlab style one based indices, subtract one from each index.

    I didn't check it, but I guess your index should be...

    int idx = I*m+J*N*m*m+i+j*N*m;