MATLAB Function Reference
eval

Execute a string containing a MATLAB expression

Syntax

• ```eval(expression)
eval(expression,catch_expr)
[a1,a2,a3,...] = eval(function(b1,b2,b3,...))
```

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,...]
```

```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.

```[a1,a2,a3,...] = eval(function(b1,b2,b3,...)) ``` executes `function` with arguments `b1,b2,b3,...`, and returns the results in the specified output variables.

Remarks

Using the `eval` output argument list is recommended over including the output arguments in the expression string. The first syntax below avoids strict checking by the MATLAB parser and can produce untrapped errors and other unexpected behavior.

• ```eval('[a1,a2,a3,...] = function(var)')      % not recommended
[a1,a2,a3,...] = eval('function(var)')      % recommended syntax
```

Examples

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
```

This example uses a function `showdemo` that runs a MATLAB demo selected by the user. If an error is encountered, a message is displayed that names the demo that failed.

• ```function showdemo(demos)
errstring = 'Error running demo: ';
n = input('Select a demo number: ');
eval(demos(n,:),'[errstring demos(n,:)]')
% ----- end of file showdemo.m -----

showdemo(D)
Select a demo number: 2

ans =

```

The next example executes the size function on a 3-dimensional array, returning the array dimensions in output variables `d1`, `d2`, and `d3`.

• ```A = magic(4);
A(:,:,2) = A';

[d1,d2,d3] = eval('size(A)')

d1 =
4

d2 =
4

d3 =
2
```

`assignin`, `catch`, `evalin`, `feval`, `lasterr`, `try`