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.
344 <strong>Chapter</strong> 4 <strong>Programm<strong>in</strong>g</strong> <strong>in</strong> <strong>Matlab</strong><br />
Let’s look at a function m-file that sends two outputs back to <strong>the</strong> call<strong>in</strong>g<br />
program or <strong>Matlab</strong> command workspace.<br />
◮ Example 7. Write a function m-file that will compute <strong>the</strong> area and circumference<br />
<strong>of</strong> a circle <strong>of</strong> radius r.<br />
Open <strong>the</strong> editor and enter <strong>the</strong> follow<strong>in</strong>g l<strong>in</strong>es.<br />
function [area,circumference]=area_and_circumference(r)<br />
area=pi*r^2;<br />
circumference=2*pi*r;<br />
Save <strong>the</strong> file as area_and_circumference.m. Set <strong>the</strong> radius <strong>of</strong> a particular<br />
circle at <strong>the</strong> <strong>Matlab</strong> prompt.<br />
>> radius=12;<br />
Call <strong>the</strong> function area_and_circumference with <strong>in</strong>put argument radius and<br />
store <strong>the</strong> result<strong>in</strong>g area and circumference <strong>in</strong> <strong>the</strong> workspace variables A and C.<br />
>> [A,C]=area_and_circumference(radius)<br />
A =<br />
452.3893<br />
C =<br />
75.3982<br />
Functions return output variables <strong>in</strong> <strong>the</strong> order <strong>in</strong> which <strong>the</strong>y are listed <strong>in</strong> <strong>the</strong><br />
function def<strong>in</strong>ition l<strong>in</strong>e with<strong>in</strong> <strong>the</strong> m-file. Thus,<br />
[area,circumference]=area_and_circumference(r)<br />
declares that area will be <strong>the</strong> first output returned and circumference will be<br />
<strong>the</strong> second.<br />
It is not required that <strong>the</strong> call<strong>in</strong>g statement (whe<strong>the</strong>r from <strong>the</strong> command l<strong>in</strong>e,<br />
a script, or ano<strong>the</strong>r function) conta<strong>in</strong> <strong>the</strong> same number <strong>of</strong> output variables as<br />
def<strong>in</strong>ed by <strong>the</strong> function m-file. If you specify fewer output variables <strong>in</strong> <strong>the</strong> call<strong>in</strong>g<br />
statement than are def<strong>in</strong>ed <strong>in</strong> <strong>the</strong> function m-file, <strong>the</strong> output variables <strong>in</strong> <strong>the</strong>