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.

5 Types of Functions<br />

Using a Subfunction<br />

function h = sCountFun(X)<br />

h = @subCount;<br />

count = X<br />

subCount(0, count);<br />

function subCount(incr, ini)<br />

persistent count;<br />

initializing = nargin > 1;<br />

if initializing<br />

count = ini; else<br />

count = count + incr<br />

end<br />

Using a Nested Function<br />

function h = nCountFun(X)<br />

h = @nestCount;<br />

count = X<br />

function nestCount(incr)<br />

count = count + incr<br />

end<br />

end<br />

When sCountFun executes, it passes the initial value for count to the<br />

subCount subfunction. Keep in mind that the count variable in sCountFun is<br />

not the same as the count variable in subCount; they are entirely independent<br />

of each other. Whenever subCount is called via its function handle, the value<br />

for count comes from its persistent place in memory.<br />

In nestCount, thecount variable again gets its value from the primary<br />

function when called from within the M-file. However, in this case the count<br />

variable in the primary and nested functions are one and the same. When<br />

nestCount is called by means of its function handle, the value for count is<br />

assigned from its storage within the function handle.<br />

Running the Example. The subCount and nestCount functions increment a<br />

value in memory by another value that you pass as an input argument. Both<br />

of these functions give the same results.<br />

Get the function handle to nestCount, and initialize the count value to a<br />

four-element vector:<br />

h = nCountFun([100 200 300 400])<br />

count =<br />

100 200 300 400<br />

Increment the persistent vector by 25, and then by 42:<br />

h(25)<br />

5-24

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

Saved successfully!

Ooh no, something went wrong!