Pass Matrices

In MATLAB®, you can pass matrices into and out of MEX-files written in Fortran. You can manipulate the MATLAB arrays by using mxGetPr and mxGetPi to assign pointers to the real and imaginary parts of the data stored in the MATLAB arrays. You can create new MATLAB arrays from within your MEX-file by using mxCreateDoubleMatrix.

The example matsq.F takes a real 2-by-3 matrix and squares each element. To see the source code, open the fileopen the file in MATLAB Editor.

After performing error checking to ensure that the correct number of inputs and outputs was assigned to the gateway subroutine and to verify the input was in fact a numeric matrix, matsq.F creates a matrix. The matrix is copied to a Fortran matrix using mxCopyPtrToReal8. Now the computational subroutine can be called, and the return argument is placed into y_pr, the pointer to the output, using mxCopyReal8ToPtr.

To build this example, at the command prompt type:

mex matsq.F

For a 2-by-3 real matrix, type:

x = [1 2 3; 4 5 6];
y = matsq(x)
y =
    1      4      9
   16     25     36

See Also

| |

Was this topic helpful?