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.
Section 4.3 Functions <strong>in</strong> <strong>Matlab</strong> 357<br />
n=7;<br />
nterm=fib(n);<br />
fpr<strong>in</strong>tf(’The n = %d term <strong>of</strong> <strong>the</strong> sequence is: %d\n’, n,nterm)<br />
The output is correct.<br />
The n = 7 term <strong>of</strong> <strong>the</strong> sequence is: 13<br />
Readers should check <strong>the</strong> behavior for o<strong>the</strong>r values <strong>of</strong> n.<br />
19. Save <strong>the</strong>se l<strong>in</strong>es as tw<strong>in</strong>primes.m. The || is <strong>Matlab</strong>’s “short-circuit or.” If<br />
<strong>the</strong> first <strong>the</strong> first part <strong>of</strong> <strong>the</strong> “or” expression evaluates as true, <strong>the</strong>n <strong>the</strong> <strong>in</strong>terpreter<br />
doesn’t bo<strong>the</strong>r with <strong>the</strong> second part <strong>of</strong> <strong>the</strong> “or” expression, as it is already true.<br />
Note that we’ve also <strong>in</strong>cluded an error message, which when executed, displays<br />
to <strong>the</strong> command w<strong>in</strong>dow and stops program execution.<br />
function tw<strong>in</strong>s=tw<strong>in</strong>primes(a,b)<br />
if round(a)~=a || round(b)~=b<br />
error(’The <strong>in</strong>puts a and b must be <strong>in</strong>tegers.’)<br />
end<br />
candidates=a:b;<br />
tw<strong>in</strong>s=[];<br />
candidates=candidates(isprime(candidates));<br />
len=length(candidates);<br />
for k=1:(len-1)<br />
if candidates(k+1)-candidates(k)==2<br />
tw<strong>in</strong>s=[tw<strong>in</strong>s;candidates(k:k+1)];<br />
end<br />
end<br />
Test <strong>the</strong> function.