Documentation

eval

ExecuteMATLABexpression in text

Syntax

eval(expression)
[output1,...,outputN] = eval(expression)

Description

eval(expression)evaluates the MATLAB®code represented byexpression. If you useevalwithin an anonymous function, nested function, or function that contains a nested function, the evaluatedexpressioncannot create a variable.

[output1,...,outputN] = eval(expression)stores output fromexpressionin the specified variables.

Input Arguments

expression

Character vector or string scalar that contains a valid MATLAB expression.

To include a numeric value in the expression, convert it to a character vector or string scalar.

Output Arguments

output1,...,outputN

Outputs from the evaluatedexpression.

Examples

collapse all

Select a matrix to plot at runtime.

This example requires that you have a matrix in the current workspace. For example:

aMatrix = magic(5);

Interactively request the name of a matrix to plot, and callevalto use its value.

expression = input('Enter the name of a matrix: ','s');if(exist(expression,'var')) mesh(eval(expression))end

If you typeaMatrixat the input prompt, this code creates a mesh plot ofmagic(5).

Tips

  • Many common uses of theevalfunction are less efficient and are more difficult to read and debug than other MATLAB functions and language constructs. For more information, see替代eval函数.

  • Whenever possible, do not include output arguments within the input to theevalfunction, such aseval(['output = ',expression]). The preferred syntax,

    output = eval(expression)

    allows the MATLAB parser to perform stricter checks on your code, preventing untrapped errors and other unexpected behavior.

Introduced before R2006a

Was this topic helpful?