15.11.2014 Views

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

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

334 <strong>Chapter</strong> 4 <strong>Programm<strong>in</strong>g</strong> <strong>in</strong> <strong>Matlab</strong><br />

That is, you specify <strong>the</strong> variable hold<strong>in</strong>g <strong>the</strong> function handle, followed by a comma<br />

separated list <strong>of</strong> arguments <strong>in</strong> paren<strong>the</strong>ses.<br />

◮ Example 1. Create a function to emulate <strong>the</strong> behavior <strong>of</strong> <strong>the</strong> ma<strong>the</strong>matical<br />

function f(x) = 2x 2 − 3.<br />

We use <strong>the</strong> syntax fhandle = @(arglist) expr to create and store a function<br />

handle <strong>in</strong> <strong>the</strong> variable f.<br />

>> f = @(x) 2*x^2 - 3<br />

f =<br />

@(x) 2*x^2 - 3<br />

We now execute <strong>the</strong> function by specify<strong>in</strong>g <strong>the</strong> function handle associated with<br />

it, followed by a s<strong>in</strong>gle argument (<strong>the</strong> <strong>in</strong>put) <strong>in</strong> paren<strong>the</strong>ses.<br />

>> f(3)<br />

ans =<br />

15<br />

However, note what happens when we pass an array as <strong>in</strong>put to this function.<br />

>> x=0:5<br />

x =<br />

0 1 2 3 4 5<br />

>> f(x)<br />

??? Error us<strong>in</strong>g ==> mpower<br />

Matrix must be square.<br />

Error <strong>in</strong> ==> @(x) 2*x^2 - 3<br />

We’ve failed to make our function “array smart.” You cannot square a vector, as<br />

we are rem<strong>in</strong>ded <strong>in</strong> <strong>the</strong> error message “Matrix must be square.” We need to use<br />

array operators to make our anonymous function “array smart.”<br />

>> f = @(x) 2*x.^2 -3<br />

f =<br />

@(x) 2*x.^2 -3

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

Saved successfully!

Ooh no, something went wrong!