eval - Execute string containing MATLAB® expression

Syntax

eval(expression)
[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, ...]

[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. Use the second syntax instead:

% Not recommended
  eval('[a1, a2, a3, ...] = function(var)')

% Recommended syntax
  [a1, a2, a3, ...] = eval('function(var)')   

Examples

Example 1 – Working with a Series of Files

Load MAT-files August1.mat to August10.mat into the MATLAB workspace:

for d=1:10
   s = ['load August' int2str(d) '.mat']
   eval(s)
end

These are the strings being evaluated:

s =
   load August1.mat
s =
   load August2.mat
s =
   load August3.mat
      - etc. -

Example 2 – Assigning to Variables with Generated Names

Generate variable names that are unique in the MATLAB workspace and assign a value to each using eval:

for k = 1:5
   t = clock;
   pause(uint8(rand * 10));
   v = genvarname('time_elapsed', who);
   eval([v ' = etime(clock,t)'])
   end

As this code runs, eval creates a unique statement for each assignment:

time_elapsed =
    5.0070
time_elapsed1 =
    2.0030
time_elapsed2 =
    7.0010
time_elapsed3 =
    8.0010
time_elapsed4 =
    3.0040

Example 3 – Evaluating a Returned Function Name

The following command removes a figure by evaluating its CloseRequestFcn property as returned by get.

eval(get(h,'CloseRequestFcn'))

See Also

evalc, evalin, assignin, feval, catch, lasterror, try

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS