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
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Section 4.3 Functions <strong>in</strong> <strong>Matlab</strong> 339<br />
you must assign a value to each output variable before <strong>the</strong> function def<strong>in</strong>ition is<br />
complete.<br />
Before gett<strong>in</strong>g too ambitious, let’s start with some simple examples <strong>of</strong> function<br />
M-files that emulate <strong>the</strong> behavior <strong>of</strong> <strong>the</strong> anonymous functions <strong>in</strong> Examples 1<br />
through 3.<br />
◮ Example 4.<br />
f(x) = 2x 2 − 3.<br />
Write a function m-file to emulate <strong>the</strong> behavior <strong>of</strong> <strong>the</strong> function<br />
Open <strong>the</strong> <strong>Matlab</strong> editor and enter <strong>the</strong> follow<strong>in</strong>g l<strong>in</strong>es.<br />
function y=f(x)<br />
y=2*x^2-3;<br />
Note how we’ve followed <strong>the</strong> syntax rules outl<strong>in</strong>ed above.<br />
i. The first word on <strong>the</strong> first l<strong>in</strong>e is <strong>the</strong> keyword function.<br />
ii. We are us<strong>in</strong>g y as <strong>the</strong> output variable. Because <strong>the</strong>re is only a s<strong>in</strong>gle output<br />
variable, <strong>the</strong> surround<strong>in</strong>g brackets are not required.<br />
iii. The function name is f.<br />
iv. F<strong>in</strong>ally, surrounded <strong>in</strong> required paren<strong>the</strong>ses is a s<strong>in</strong>gle <strong>in</strong>put variable x.<br />
Save <strong>the</strong> file as f.m. Note how we’ve attached .m to <strong>the</strong> function name f.<br />
In Example 1, we found that f(3) = 15. Let’s test <strong>the</strong> current function.<br />
Return to <strong>the</strong> command w<strong>in</strong>dow and enter <strong>the</strong> follow<strong>in</strong>g at <strong>the</strong> <strong>Matlab</strong> prompt.<br />
>> f(3)<br />
ans =<br />
15<br />
As <strong>in</strong> Example 1, <strong>the</strong> current function is not “array smart,” so attempt<strong>in</strong>g to<br />
evaluate <strong>the</strong> function on an array will fail.