Pass Arrays

Two Dimensional MATLAB Arrays

All MATLAB® data is stored columnwise, and MATLAB uses one-based indexing for subscripts. MATLAB uses these conventions because it was originally written in Fortran. To demonstrate how this may affect your MATLAB data when using C functions, create the following matrix:

m = 1:12;
m = reshape(m,4,3)
dims = size(m)
m =
     1     5     9
     2     6    10
     3     7    11
     4     8    12

dims =
     4     3

Matrix m is a 4-by-3 array.

You might need to transpose MATLAB arrays before passing them to a C function since C assumes a row by column format. The print2darray function in the shrlibsample library shows this.

 print2darray C Function

The first argument is a two dimensional array. The len argument is the number of rows. The function displays each element of the matrix. Using matrix m:

calllib('shrlibsample','print2darray',m,4)
         1         2         3
         4         5         6
         7         8         9
        10        11        12

You must transpose m to get the desired result:

calllib('shrlibsample','print2darray',m',4)
         1         5         9
         2         6        10
         3         7        11
         4         8        12

More than Two Dimensional MATLAB Arrays

When passing an array having more than two dimensions, the shape of the array might be altered by MATLAB. To ensure that the array retains its shape, store the size of the array before making the call, and then use this same size to reshape the output array to the correct dimensions. For example:

vs = size(vin)              % Store the original dimensions
vs =
     2     5     2

vout = calllib('shrlibsample','multDoubleArray',vin,20)

size(vout)                  % Dimensions have been altered
ans =
     2    10

vout = reshape(vout,vs);   % Restore the array to 2-by-5-by-2

size(vout)
ans =
     2     5     2
Was this topic helpful?