MATLAB: MEX – Multidimensional Array passing to Fortran

mex fortran multidimensional array

Hello, I want to pass back and forth a MxN matrix with K number of pages from matlab to fortran. What mex function/commands would be used to do this? I can do the 2d arrays but haven't found anything for multidimensional arrays.

Best Answer

A couple of options:
--------------------------------------
1)
See this FEX submission:
To use a MATLAB 3D variable passed in to the mex function, e.g.:
use MatlabAPImx
real*8, pointer :: X(:,:,:)
X => fpGetPr3(prhs(1)) ! Does not copy the data
Then you can use X as a regular read-only Fortran variable since it is pointing directly at the data area of the original MATLAB variable in the workspace. I.e., no copy is made. If you need to alter the contents of X then use the copy version of the function instead with an appropriate deallocation at the end:
use MatlabAPImx
real*8, pointer :: X(:,:,:)
X => fpGetPr3copy(prhs(1)) ! Copies the data
! use/modify X
call fpDeallocate(X)
To copy a 3D Fortran array back to an output variable:
use MatlabAPImx
! X is a 3D Fortran real*8 variable
plhs(1) = mxArray(X)
To copy the input to a new matrix, modify it as a Fortran 3D variable, and return the result back to MATLAB you could do this:
use MatlabAPImx
real*8, pointer :: X(:,:,:)
plhs(1) = mxDuplicateArray(prhs(1)) ! Copies the data
X => fpGetPr3(plhs(1)) ! Points to the new copy
! use/modify X
--------------------------------------
2)
Manually get and copy the contents back & forth using mxGetNumberOfDimensions, mxGetDimensions, mxGetPr, mxCopyReal8ToPtr, mxCopyPtrToReal8, and Fortran allocated variables as necessary. Or some combination of the above with the %VAL() construct if you want to avoid data copies. It gets ugly so I will not attempt to write all of the details here.