15.11.2014 Views

Chapter 4: Programming in Matlab - College of the Redwoods

Chapter 4: Programming in Matlab - College of the Redwoods

Chapter 4: Programming in Matlab - College of the Redwoods

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Section 4.6 Nested Functions <strong>in</strong> <strong>Matlab</strong> 401<br />

We’ve seen a couple <strong>of</strong> ways we can fix this M-file so that <strong>the</strong> value <strong>of</strong> x is<br />

pr<strong>in</strong>ted by <strong>the</strong> subfunction. One way would be to declare <strong>the</strong> variable x global <strong>in</strong><br />

both <strong>the</strong> primary function and <strong>the</strong> subfunction.<br />

function varScope1<br />

global x<br />

x=3;<br />

nestfun1<br />

function nestfun1<br />

global x<br />

fpr<strong>in</strong>tf(’In nestfun1, x equals: %d\n’,x)<br />

Runn<strong>in</strong>g this M-file produces <strong>the</strong> desired effect. The subfunction now has knowledge<br />

<strong>of</strong> <strong>the</strong> global variable x and its fpr<strong>in</strong>tf statement is successful.<br />

>> varScope1<br />

In nestfun1, x equals: 3<br />

We’ve also seen that we can pass <strong>the</strong> value <strong>of</strong> <strong>the</strong> variable x to an <strong>in</strong>put argument<br />

<strong>of</strong> <strong>the</strong> subfunction.<br />

function varScope1<br />

x=3;<br />

nestfun1(x)<br />

function nestfun1(x)<br />

fpr<strong>in</strong>tf(’In nestfun1, x equals: %d\n’,x)<br />

As readers can see, this also works.<br />

>> varScope1<br />

In nestfun1, x equals: 3<br />

Nested Functions Redef<strong>in</strong>e <strong>the</strong> Rules <strong>of</strong> Variable Scope. If we take our<br />

same example, and nest <strong>the</strong> subfunction, a whole new set <strong>of</strong> rules are put <strong>in</strong>to<br />

place for variable scope, <strong>the</strong> first <strong>of</strong> which follows.

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

Saved successfully!

Ooh no, something went wrong!