Documentation

This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.

Pass Arrays

print2darray Function

The print2darray function in the shrlibsample library displays the values of a 2-D array with three columns and a variable number of rows. The my2d parameter is a two-dimensional array of double. The len parameter is the number of rows.

EXPORTED_FUNCTION void print2darray(double my2d[][3],int len)
{
    int indxi,indxj;
    for(indxi=0;indxi<len;++indxi) 
    {
        for(indxj=0;indxj<3;++indxj)
        {
            mexPrintf("%10g",my2d[indxi][indxj]);
        }
        mexPrintf("\n");
    }
}

Convert MATLAB Array to C-Style Dimensions

This example shows how to pass data stored columnwise in a MATLAB array to a C function that assumes a row-by-column format.

Load the library containing the print2darray function.

if not(libisloaded('shrlibsample'))
    addpath(fullfile(matlabroot,'extern','examples','shrlib'))
    loadlibrary('shrlibsample')
end

Create a MATLAB array with 4 rows and 3 columns.

m = reshape(1:12,4,3)
m =

     1     5     9
     2     6    10
     3     7    11
     4     8    12

Display the values. The first column is [1 4 7 10] instead of [1 2 3 4].

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

Transpose m to get the desired result.

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

multDoubleArray Function

The multDoubleArray function in the shrlibsample library multiplies each element of an array by three. The function uses a single subscript (linear indexing) to navigate the input array.

EXPORTED_FUNCTION void multDoubleArray(double *x,int size)
{
    /* Multiple each element of the array by 3 */
    int i;
    for (i=0;i<size;i++)
    *x++ *= 3;
}

The MATLAB® function signature is:

Return TypeNameArguments
doublePtrmultDoubleArray(doublePtr,
int32)

Preserve 3-D MATLAB Array

This example shows how a C function changes the dimensions of a MATLAB array, and how to restore its shape.

Load the library.

if not(libisloaded('shrlibsample'))
    addpath(fullfile(matlabroot,'extern','examples','shrlib'))
    loadlibrary('shrlibsample')
end

Create a 2-by-5-by-2 input array and display its dimensions.

vin = reshape(1:20,2,5,2);
vs = size(vin)
vs =

     2     5     2

Call multDoubleArray to multiply each element. Display the dimensions of the output.

vout = calllib('shrlibsample','multDoubleArray',vin,20);
size(vout)
ans =

     2    10

Restore the original shape.

vout = reshape(vout,vs);
size(vout)
ans =

     2     5     2

Was this topic helpful?