Programming Previous page   Next Page

Evaluating Expressions

This section covers the following topics:

Find Alternatives to Using eval

While the eval function can provide a convenient solution to certain programming challenges, it is best to limit its use. The main reason is that code that uses eval is often difficult to read and hard to debug. A second reason is that eval statements cannot always be translated into C or C++ code by the MATLAB Compiler.

If you are evaluating a function, it is more efficient to use feval than eval. The feval function is made specifically for this purpose and is optimized to provide better performance.

For more information: See MATLAB Technical Note 1103, "What Is the EVAL Function, When Should I Use It, and How Can I Avoid It?" at URL http://www.mathworks.com/support/tech-notes/1100/1103.html.

Assigning to a Series of Variables

One common pattern for creating variables is to use a variable name suffixed with a number (e.g., phase1, phase2, phase3, etc.). We recommend using a cell array to build this type of variable name series, as it makes code more readable and executes more quickly than some other methods. For example:

Short-Circuit Logical Operators

MATLAB has logical AND and OR operators (&& and ||) that enable you to partially evaluate, or short-circuit, logical expressions. Short-circuit operators are useful when you want to evaluate a statement only when certain conditions are satisfied.

In this example, MATLAB does not execute the function myfun unless its M-file exists on the current path.

For more information: See Short-Circuit Operators in the MATLAB Programming documentation.

Changing the Counter Variable within a for Loop

You cannot change the value of the loop counter variable (e.g., the variable k in the example below) in the body of a for loop. For example, this loop executes just 10 times, even though k is set back to 1 on each iteration.

Although MATLAB does allow you to use a variable of the same name as the loop counter within a loop, this is not a recommended practice.


Previous page  Strings MATLAB Path Next page

© 1994-2005 The MathWorks, Inc.