MATLAB Application Program Interface Reference | Help Desk |
mexEvalString
Execute a MATLAB command in the workspace of the caller
#include "mex.h" int mexEvalString(const char *command);command
A string containing the MATLAB command to execute.
0 if successful, and a nonzero value if unsuccessful. CallmexEvalString
to invoke a MATLAB command
in the workspace of the caller.
mexEvalString
and mexCallMATLAB
both execute MATLAB commands. However, mexCallMATLAB
provides a mechanism for returning results (left-hand side arguments) back to the MEX-file; mexEvalString
provides no way for return values to be passed back to the MEX-file.
All arguments that appear to the right of an equals sign in the command
string must already be current variables of the caller's workspace.
Consider an M-file named FibSqr.m
that invokes a MEX-file named CalcFib
:
function r = FibSqr(n) CalcFib(n); % CalcFib loads the nth Fibonacci number into variable fib. r = fib .^ 2;Suppose the
CalcFib
calculates the nth Fibonacci number. (MEX-files tend to calculate Fibonacci numbers significantly faster than M-files.) CalcFib
calls mexEvalString
to write the result into a variable named fib
.
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { int n, c, status; double answer, most_recent, next_most_recent; char command_string[20]; /* Find the nth Fibonacci number. */ n = (int)mxGetScalar(prhs[0]); if (n < 1) mexErrMsgTxt("First argument must be positive"); else if (n<3) mexEvalString("fib = 1;"); else { for (most_recent=1, next_most_recent=1, c=3; c<=n; c++) { answer = most_recent + next_most_recent; next_most_recent = most_recent; most_recent = answer; } sprintf(command_string, "fib = %g", answer); status = mexEvalString(command_string); if (status) mexErrMsgTxt("Could not Calculate this Squibonacci number."); } }Invoking
FibSqr
yields
>> FibSqr(7)); fib = 13 ans = 169For an additional example, see
mexEvalString.c
in the mex
subdirectory of the examples
directory.
mexCallMATLAB