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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

N=20;<br />

for a=1:N<br />

for b=1:N<br />

for c=1:N<br />

if (c^2==a^2+b^2)<br />

fpr<strong>in</strong>tf(’Pythagorean Triple: %d, %d, %d\n’, a, b, c)<br />

end<br />

end<br />

end<br />

end<br />

7. The follow<strong>in</strong>g loop will sum <strong>the</strong> first 20 terms.<br />

N=20;<br />

s=0;<br />

for k=1:N;<br />

s=s+(-1)^(k+1)/(2*k-1);<br />

end<br />

Compute <strong>the</strong> relative error <strong>in</strong> approximat<strong>in</strong>g π/4 with <strong>the</strong> sum <strong>of</strong> <strong>the</strong> first 20<br />

terms.<br />

rel=abs(s-pi/4)/abs(pi/4);<br />

Output <strong>the</strong> results.<br />

fpr<strong>in</strong>tf(’The actual value <strong>of</strong> pi/4 is %.6f.\n’,pi/4)<br />

fpr<strong>in</strong>tf(’The sum <strong>of</strong> <strong>the</strong> first %d terms is %f.\n’,N,s)<br />

fpr<strong>in</strong>tf(’The relative error is %.2e.\n’,rel)<br />

9. The mod(m,primes)==0 comparison will produce a logical vector which<br />

conta<strong>in</strong>s a 1 <strong>in</strong> each position that <strong>in</strong>dicates that <strong>the</strong> current number m is divisible<br />

by <strong>the</strong> number <strong>in</strong> <strong>the</strong> prime vector <strong>in</strong> <strong>the</strong> correspond<strong>in</strong>g position. If “any” <strong>of</strong><br />

<strong>the</strong>se are 1’s, <strong>the</strong>n <strong>the</strong> number m is divisible by at least one <strong>of</strong> <strong>the</strong> primes <strong>in</strong> <strong>the</strong><br />

current list primes. In that case, we cont<strong>in</strong>ue to <strong>the</strong> next value <strong>of</strong> m. O<strong>the</strong>rwise,<br />

we append m to <strong>the</strong> list <strong>of</strong> primes.

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

Saved successfully!

Ooh no, something went wrong!