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.

Section 4.3 Functions <strong>in</strong> <strong>Matlab</strong> 359<br />

Looks correct.<br />

23. Enter <strong>the</strong> follow<strong>in</strong>g l<strong>in</strong>es and save a pascalTriangle.m.<br />

function pascalTriangle(rows)<br />

for n=0:rows<br />

row=[];<br />

format=’’;<br />

for k=0:n<br />

row=[row,b<strong>in</strong>om(n,k)];<br />

format=[format,’%6d’];<br />

end<br />

format=[format,’\n’];<br />

fpr<strong>in</strong>tf(format,row)<br />

end<br />

This function will only work if you have written a successful b<strong>in</strong>omial coefficient<br />

function b<strong>in</strong>om.m (see Exercise 22), ei<strong>the</strong>r with a persnalized myfactorial.m<br />

(see Exercise 21) or <strong>Matlab</strong>’s built <strong>in</strong> factorial.m. Execute <strong>the</strong> follow<strong>in</strong>g at <strong>the</strong><br />

command prompt.<br />

>> pascalTriangle(5)<br />

1<br />

1 1<br />

1 2 1<br />

1 3 3 1<br />

1 4 6 4 1<br />

1 5 10 10 5 1<br />

27. Enter <strong>the</strong> follow<strong>in</strong>g code <strong>in</strong> <strong>the</strong> editor and save as mymax.m.

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

Saved successfully!

Ooh no, something went wrong!