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.

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

>> tw<strong>in</strong>s=tw<strong>in</strong>primes(1,100)<br />

tw<strong>in</strong>s =<br />

3 5<br />

5 7<br />

11 13<br />

17 19<br />

29 31<br />

41 43<br />

59 61<br />

71 73<br />

Looks good. We leave to <strong>the</strong> reader to check that we have all <strong>of</strong> <strong>the</strong> tw<strong>in</strong><br />

primes between 1 and 100.<br />

21. Save <strong>the</strong> follow<strong>in</strong>g l<strong>in</strong>es as myfactorial.m. Aga<strong>in</strong> we’re error check<strong>in</strong>g. If<br />

n is not an <strong>in</strong>teger <strong>of</strong> if it is not <strong>the</strong> case that n is nonnegative, we send an<br />

error message to <strong>the</strong> command w<strong>in</strong>dow and halt program execution. The && is<br />

<strong>Matlab</strong>’s “short-circuit and.” If <strong>the</strong> first part <strong>of</strong> <strong>the</strong> and statement evaluates as<br />

false, <strong>the</strong> <strong>in</strong>terpreter doesn’t bo<strong>the</strong>r with <strong>the</strong> second part <strong>of</strong> <strong>the</strong> “and” statement,<br />

sav<strong>in</strong>g some time.<br />

function fact=myfactorial(n)<br />

if round(n)~=n or ~(n>=0)<br />

error(’n must be a nonnegative <strong>in</strong>teger’)<br />

end<br />

if n==0<br />

fact=1;<br />

else<br />

fact=prod(1:n);<br />

end<br />

Check<strong>in</strong>g.<br />

>> fact=myfactorial(0)<br />

fact =<br />

1<br />

>> fact=myfactorial(5)<br />

fact =<br />

120

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

Saved successfully!

Ooh no, something went wrong!