MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Alternatives to the eval Function


In this section...
“Why Avoid the eval Function?” on page 2-87
“Variables with Sequential Names” on page 2-87
“Files with Sequential Names” on page 2-88
“Function Names in Variables” on page 2-89
“Field Names in Variables” on page 2-89
“Error Handling” on page 2-90

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:

Alternatives to the eval Function
Free download pdf