Alternatives to the eval Function
In this section...
“Why Avoid the eval Function?” on page 2-86
“Variables with Sequential Names” on page 2-86
“Files with Sequential Names” on page 2-87
“Function Names in Variables” on page 2-87
“Field Names in Variables” on page 2-88
“Error Handling” on page 2-88
Why Avoid the eval Function?
Although the eval function is very powerful and flexible, it is 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.
• Concatenated character vectors within an eval statement are 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
2 Program Components
2-86
Précédent

- 136/1450

Suivant