MATLAB cannot perform any performance optimization on statements called by
eval
. This can cause code to run less efficiently.
eval
statements make code less clear and cause issues
with sharing and maintaining code. One 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.
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:
Old | New |
---|---|
eval(['A', int2str(n),' = magic(n)'])
|
numArrays = 10;
|
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
For more information see Alternatives to the eval Function.