23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Nested Functions<br />

count =<br />

125 225 325 425<br />

h(42)<br />

count =<br />

167 267 367 467<br />

Now do the same using sCountFun and subCount, and verify that the results<br />

are the same.<br />

Note If you construct a new function handle to subCount or nestCount, the<br />

former value for count is no longer retained in memory. It is replaced by<br />

the new value.<br />

Separate Instances of Externally Scoped Variables<br />

The code shown below constructs two separate function handles to the same<br />

nested function, nestCount, that was used in the last example. It assigns<br />

the handles to fields counter1 and counter2 of structure s. These handles<br />

reference different instances of the nestCount function. Each handle also<br />

maintains its own separate value for the externally scoped count variable.<br />

Call nCountFun twicetogettwoseparatefunctionhandlestonestCount.<br />

Initialize the two instances of count to two different vectors:<br />

s.counter1 = nCountFun([100 200 300 400]);<br />

count =<br />

100 200 300 400<br />

s.counter2 = nCountFun([-100 -200 -300 -400]);<br />

count =<br />

-100 -200 -300 -400<br />

Now call nestCount by means of each function handle to demonstrate that<br />

<strong>MATLAB</strong> increments the two count variables individually.<br />

Increment the first counter:<br />

s.counter1(25)<br />

5-25

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

Saved successfully!

Ooh no, something went wrong!