| MATLAB Function Reference | Search  Help Desk |
| eval | Examples See Also |
Execute a string containing a MATLAB expression
Syntax
eval(expression) [a1,a2,a3,...] = eval(expression) eval(expression,catch_expr)
Description
eval(expression)
executes expression, a string containing any valid MATLAB expression. You can construct expression by concatenating substrings and variables inside square brackets:
expression= [string1,int2str(var),string2,...]
[a1,a2,a3,...] = eval(expression)
executes expression and returns the results in the specified output variables. Using the eval output argument list is recommended over including the output arguments in the expression string:
eval('[a1,a2,a3,...] = function(var)')
The above syntax avoids strict checking by the MATLAB parser and can produce untrapped errors and other unexpected behavior.
eval(expression,catch_expr)
executes expression and, if an error is detected, executes the catch_expr string. If expression produces an error, the error string can be obtained with the lasterr function. This syntax is useful when expression is a string that must be constructed from substrings. If this is not the case, use the try...catch control flow statement in your code.
Examples
This example executes a simple MATLAB expression:A = '1+4';
aval = eval(A)
aval =
5
This for loop generates a sequence of 12 matrices named M1 through M12:
for n = 1:12
magic_str = ['M',int2str(n),' = magic(n)'];
eval(magic_str)
end
See Also
assignin, catch, evalin, feval, lasterr, try