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
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Section 4.3 Functions <strong>in</strong> <strong>Matlab</strong> 343<br />
>> clear A B C<br />
>> global A B C<br />
>> A=2; B=3; C=-4;<br />
You must also declare <strong>the</strong>se constants as global <strong>in</strong> <strong>the</strong> function m-file.<br />
function w=f(x,y,z)<br />
global A B C<br />
w=A*x+B*y+C*z;<br />
Resave <strong>the</strong> function m-file as f.m. Note that we’ve made two changes.<br />
i. We’ve removed A, B, and C as <strong>in</strong>put arguments. The first l<strong>in</strong>e <strong>of</strong> <strong>the</strong> function<br />
file now reads function w=f(x,y,z).<br />
ii. We’ve declared <strong>the</strong> variables A, B, and C as global. Now, any changes to <strong>the</strong><br />
global variables <strong>in</strong> <strong>the</strong> command workspace will be recognized by <strong>the</strong> variables<br />
<strong>in</strong> <strong>the</strong> function workspace, and vice-versa, any change to <strong>the</strong> global variables<br />
<strong>in</strong> <strong>the</strong> function’s workspace will be recognized by <strong>the</strong> command workspace. In<br />
effect, <strong>the</strong> two workspaces share <strong>the</strong> values assigned to <strong>the</strong> global variables.<br />
Evaluate <strong>the</strong> function at (x, y, z) = (−1, 2, −3).<br />
>> f(-1,2,-3)<br />
ans =<br />
16<br />
More Than One Output<br />
To this po<strong>in</strong>t, anonymous functions can seem<strong>in</strong>gly do everyth<strong>in</strong>g that we’ve<br />
demonstrated via function m-files <strong>in</strong> Examples 4-6. However, two key facts<br />
about anonymous functions expla<strong>in</strong> why we should cont<strong>in</strong>ue to explore function<br />
m-files <strong>in</strong> more depth.<br />
1. Anonymous functions are allowed only one output.<br />
2. The body <strong>of</strong> an anonymous function is allowed exactly one valid <strong>Matlab</strong> expression.