Alternatives to the eval Function
Why Avoid the eval Function?
Although the eval
function is very powerful and flexible, it not always the best solution to a programming problem. Code that calls eval
is often less efficient and more difficult to read and debug than code that uses other functions or language constructs. For example:
-
MATLAB® compiles code the first time you run it to enhance performance for future runs. However, because code in an
eval
statement can change at run time, it is not compiled. -
Code within an
eval
statement can unexpectedly create or assign to a variable already in the current workspace, overwriting existing data. -
Concatenating strings within an
eval
statement is often difficult to read. Other language constructs can simplify the syntax in your code.
For many common uses of eval
, there are preferred alternate approaches, as shown in the following examples.
Variables with Sequential Names
A frequent use of the eval
function is to create sets of variables such as A1
, A2
, ...
, An
, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array. If the data sets are of different types or sizes, use a structure or cell array.
For example, create a cell array that contains 10 elements, where each element is a numeric array:
numArrays = 10;
A = cell(numArrays,1);
for n = 1:numArrays
A{n} = magic(n);
end
Access the data in the cell array by indexing with curly braces. For example, display the fifth element of A
:
A{5}
ans =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
The assignment statement A{n} = magic(n)
is more elegant and efficient than this call to eval
:
eval(['A', int2str(n),' = magic(n)']) % Not recommended
For more information, see:
Files with Sequential Names
Related data files often have a common root name with an integer index, such as myfile1.mat
through myfileN.mat
. A common (but not recommended) use of theeval
function is to construct and pass each file name to a function using command syntax, such as
eval(['save myfile',int2str(n),'.mat']) % Not recommended
The best practice is to use function syntax, which allows you to pass variables as inputs. For example:
currentFile = 'myfile1.mat';
save(currentFile)
You can construct file names within a loop using the sprintf
function (which is usually more efficient than int2str
), and then call the save
function without eval
. This code creates 10 files in the current folder:
numFiles = 10;
for n = 1:numFiles
randomData = rand(n);
currentFile = sprintf('myfile%d.mat',n);
save(currentFile,'randomData')
end
For more information, see:
Function Names in Variables
A common use of eval
is to execute a function when the name of the function is in a variable string. There are two ways to evaluate functions from variables that are more efficient than using eval
:
-
Create function handles with the
@
symbol or with thestr2func
function. For example, run a function from a list stored in a cell array:examples = {@odedemo,@sunspots,@fitdemo}; n = input('Select an example (1, 2, or 3): '); examples{n}()
-
Use the
feval
function. For example, call a plot function (such asplot
,bar
, orpie
) with data that you specify at run time:plotFunction = input('Specify a plotting function: ','s'); data = input('Enter data to plot: '); feval(plotFunction,data)
Field Names in Variables
Access data in a structure with a variable field name by enclosing the expression for the field in parentheses. For example:
myData.height = [67, 72, 58];
myData.weight = [140, 205, 90];
fieldName = input('Select data (height or weight): ','s');
dataToUse = myData.(fieldName);
If you enter weight
at the input prompt, then you can find the minimum weight
value with the following command.
min(dataToUse)
ans =
90
For an additional example, see Generate Field Names from Variables.
Error Handling
The preferred method for error handling in MATLAB is to use a try, catch
statement. For example:
try
B = A;
catch exception
disp('A is undefined')
end
If your workspace does not contain variable A
, then this code returns:
A is undefined
Previous versions of the documentation for the eval
function include the syntax eval(expression,catch_expr)
. If evaluating the expression
input returns an error, then eval
evaluates catch_expr
. However, an explicit try/catch
is significantly clearer than an implicit catch in an eval
statement. Using the implicit catch is not recommended.