23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Nested Functions<br />

Type of Operation<br />

Evaluating an expression using<br />

eval or evalin, or assigning a<br />

variable with assignin<br />

Loading variables from a<br />

MAT-file with the load function<br />

Assigning to a variable in a<br />

<strong>MATLAB</strong> script<br />

Assigning to a variable in the<br />

<strong>MATLAB</strong> debugger<br />

How to Avoid Using Dynamic<br />

Assignment<br />

As a general suggestion, it is best to avoid<br />

using the eval, evalin, andassignin<br />

functions altogether.<br />

Use the form of load that returns a<br />

<strong>MATLAB</strong> structure.<br />

Convert the script to a function, where<br />

argument- and result-passing can often<br />

clarify the code as well.<br />

You can declare the variable to be<br />

global. For example, to create a variable<br />

X for temporary use in debugging, use<br />

K>> global X;<br />

X = value<br />

One way to avoid this error in the other cases is to pre-declare the variable in<br />

the desired function.<br />

Examples of Nested Functions<br />

This section shows a few examples of how you can use nested functions. These<br />

examples are intended to show you how to program with this type of function.<br />

For more mathematically oriented examples, see the <strong>MATLAB</strong> Mathematics<br />

documentation.<br />

Theexamplesinthissectioninclude<br />

• “Example 1 — Creating a Function Handle for a Nested Function” on page<br />

5-27<br />

• “Example 2 — Function-Generating Functions” on page 5-29<br />

Example 1 — Creating a Function Handle for a Nested Function<br />

The following example constructs a function handle for a nested function and<br />

then passes the handle to the <strong>MATLAB</strong> fplot function to plot the parabola<br />

5-27

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!