mexEvalString("p=plot(1:10);");
would generate a plot of 1 to 10 in the current figure window. Note
that since the command is evaluated in the calling function's workspace,
the variable p is stored in the calling function's workspace. Thus, if
the MEX-file were to be called from within an M-file function, p would
be stored in that function's workspace, not the main workspace.
Although
mexEvalString
is easy to code, the string passed to
mexEvalString
is evaluated by MATLAB, therefore, the MATLAB parser has to be called.
Calling another MEX-file via
mexEvalString
is not very efficient since
the MATLAB parser is called. Also, all variables created by the
mexEvalString
command are stored in the workspace of the function text called by the
MEX-file, which may need to be retrieved with the
mexGet*
functions. A
more efficient way to accomplish the same goal is to use the
mexCallMATLAB
function (assuming you're calling a function and not a script).
Using
mexCallMATLAB
Other MATLAB functions including built-in functions, MEX-file and M-file
functions (not M-file scripts) can be called from within a MEX-file using
the
mexCallMATLAB
function.
This function accepts five inputs. The first four are structured as integers, exactly
the same as the inputs to
mexFunction
:
nlhs, plhs, nrhs,
and
prhs
.
plhs and prhs are pointers to arrays of mxArrays. You set up nrhs, prhs, and nlhs to contain what you
want passed to the MATLAB function that you are calling. The function returns any output data in plhs.
Thus, it is as if your MEX-file is acting as the MATLAB parser, arranging the data in the correct data
structure and passing it to the function. The fifth argument is a character string containing the name of the
MATLAB function to be called. The following is an example of this that calculates the determinant
of a matrix and prints it out. The example assumes the matrix pointer array_ptr has already been
initialized to contain valid data.
int nlhs1, nrhs1; /*chances are plhs and prhs are
already used by mexFunction */
mxArray *plhs1[1], *prhs1[1];
prhs1 = 1; /* One output requested from the
'det' function */
prhs1 = 1; /* One input passed to the 'det'
function */
prhs1[0] = array_ptr; /* Set up input argument to 'det' */
mexCallMATLAB(nlhs1,plhs1,nrhs1,prhs1,"det");
mexPrintf("Det(array_ptr) == %g",mxGetScalar(plhs1[0]));
Section 18: Additional MEX examples
The MATLAB External Interfaces Guide has several example MEX-files
dealing with different types of data including scalars, strings, structures,
cell arrays, and sparse arrays.
If you are writing FORTRAN MEX-files, similar examples can be found here.
Section 19: Custom options files
http://www.mathworks.com/support/tech