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.

5 Types of Functions<br />

You can now use this variable as a means of calling findCube from outside<br />

of its M-file:<br />

cubeIt(8)<br />

ans =<br />

512<br />

Note When calling a function by means of its handle, use the same syntax<br />

as if you were calling a function directly. But instead of calling the function<br />

by its name (e.g., strcmp(S1, S2)), use the variable that holds the function<br />

handle (e.g., fhandle(S1, S2)).<br />

Function Handles and Nested Function Variables<br />

One characteristic of nested functions that makes them different from<br />

other <strong>MATLAB</strong> functions is that they can share nonglobal variables with<br />

certain other functions within the same M-file. A nested function nFun can<br />

share variables with any outer function that contains nFun, andwithany<br />

function nested within nFun. This characteristic has an impact on how certain<br />

variables are stored when you construct a handle for a nested function.<br />

Defining Variables When Calling Via Function Handle. The example<br />

below shows a primary function getHandle that returns a function handle for<br />

the nested function nestFun. ThenestFun function uses three different types<br />

of variables. The VLoc variable is local to the nested function, VInp is passed in<br />

when the nested function is called, and VExt is defined by the outer function:<br />

function h = getHandle(X)<br />

h = @nestFun;<br />

VExt = someFun(X);<br />

function nestFun(VInp)<br />

VLoc = 173.5;<br />

doSomeTask(VInp, VLoc, VExt);<br />

end<br />

end<br />

As with any function, when you call nestFun, you must ensure that you<br />

supply the values for any variables it uses. This is a straightforward matter<br />

5-22

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

Saved successfully!

Ooh no, something went wrong!