eval

Evaluates MATLAB code held in a character vector.

Category: Programming > Programming Utilities

Syntax

eval(expression)

Runs the code in expression as if it had been typed at that point.

eval(expression, catchExpr)

Runs catchExpr instead if expression raises an error.

[a, b] = eval(expression)

Captures the outputs of an expression that returns values.

Description

The text is parsed and executed in the workspace of the caller, so variables it creates or changes are visible afterwards, and results of statements without a semicolon are displayed as usual. This makes eval flexible but hard to read and debug; indexing with dynamic field names, cell arrays or function handles is usually a better design than building variable names as text.

With two arguments, a syntax error or run-time error in the first is caught and the second is evaluated instead.

Input arguments

expression
Text holding one or more statements or an expression.
catchExpr
Text with code to run if expression fails; the error can be read with lasterr or MException.last.

Output arguments

a, b
Values returned by the evaluated expression.

Example

Evaluating text, with a fallback

eval('a = 3 + 4')
eval('bad syntax here(', 'disp(''caught'')')
v = eval('2^5')
Output
a = 7
caught
v = 32

See also

evalc evalin feval str2func run