MATLAB Application Program Interface | Search  Help Desk |
mexCallMATLAB | Examples See Also |
Call a MATLAB function, or a user-defined M-file or MEX-file
#include "mex.h" int mexCallMATLAB(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[], const char *command_name);nlhs
mxArray
s. The called command puts pointers to the resultant mxArray
s into plhs
. Note that the called command allocates dynamic memory to store the resultant mxArray
s. By default, MATLAB automatically deallocates this dynamic memory when you clear the MEX-file. However, if heap space is at a premium, you may want to call mxDestroyArray
as soon as you are finished with the mxArray
s that plhs
points to.
nrhs
command_name
is an operator, just place the operator inside a pair of single quotes; for example, '+'
.
0 if successful, and a nonzero value if unsuccessful.
Call mexCallMATLAB
to invoke internal MATLAB numeric functions, MATLAB operators, M-files, or other MEX-files. See mexFunction
for a complete description of the arguments.
By default, if command_name
detects an error, MATLAB terminates the MEX-file and returns control to the MATLAB prompt. If you want a different error behavior, turn on the trap flag by calling mexSetTrapFlag
.
Note that it is possible to generate an object of type mxUNKNOWN_CLASS using mexCallMATLAB
. For example, if you create an M-file that returns two variables but only assigns one of them a value,
function [a,b]=foo[c] a=2*c;you'll get this warning message in MATLAB:
Warning: One or more output arguments not assigned during call to 'foo'.MATLAB assigns output
b
to an empty matrix. If you then call foo
using mexCallMATLAB
, the unassigned output variable will now be of type mxUNKNOWN_CLASS.
Create a populated mxArray
and call mexCallMATLAB
to display its contents. Then, call mexCallMATLAB
a second time to calculate the eigenvalues and eigenvectors of the newly created mxArray
. Finally, call mexCallMATLAB
a third time to display the eigenvalues.
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { double pr[] = {5.2, 7.9, 1.3, 4.2}; double pi[] = {3.4, 6.5, 2.2, 9.1}; mxArray *array_ptr; int num_out, num_in; mxArray *output_array[2], *input_array[2]; /* Create a 2-by-2 populated matrix. */ array_ptr = mxCreateDoubleMatrix(2, 2, mxREAL); memcpy(mxGetPr(array_ptr), pr, sizeof(pr)); memcpy(mxGetpi(array_ptr), pi, sizeof(pi)); /* Equivalent to disp(array) */ num_out = 0; num_in = 1; input_array[0] = array_ptr; mexCallMATLAB(num_out, output_array, num_in, input_array, "disp"); /* Equivalent to [v, d] = eig(array) */ num_out = 2; num_in = 1; input_array[0] = array_ptr; mexCallMATLAB(num_out, output_array, num_in, input_array, "eig"); /* Equivalent to disp(v) */ num_out = 0; num_in = 1; input_array[0] = output_array[0]; mexCallMATLAB(num_out, output_array, num_in, input_array, "disp"); }For an additional example, see
mexcallmatlab.c
in the mex
subdirectory of the examples
directory.
mexFunction
, mexSetTrapFlag