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.

Section 4.2 Control Structures <strong>in</strong> <strong>Matlab</strong> 313<br />

Figure 4.6. A family <strong>of</strong> curves for C = −5, −3, −1, 0, 1,<br />

3, and 5.<br />

for k=[4,8,12,15,17,19,21,24]<br />

if isprime(k)<br />

fpr<strong>in</strong>tf(’Prime found, %d, exit<strong>in</strong>g loop.\n’,k)<br />

break<br />

end<br />

fpr<strong>in</strong>tf(’Current value <strong>of</strong> <strong>in</strong>dex k is: %d\n’,k)<br />

end<br />

Note that <strong>the</strong> output lists each value <strong>of</strong> k until a prime is found. The fpr<strong>in</strong>ft<br />

command issues a warn<strong>in</strong>g message and <strong>the</strong> break command term<strong>in</strong>ates <strong>the</strong> loop.<br />

Current value <strong>of</strong> <strong>in</strong>dex k is: 4<br />

Current value <strong>of</strong> <strong>in</strong>dex k is: 8<br />

Current value <strong>of</strong> <strong>in</strong>dex k is: 12<br />

Current value <strong>of</strong> <strong>in</strong>dex k is: 15<br />

Prime found, 17, exit<strong>in</strong>g loop.<br />

In this next code snippet, we want to pr<strong>in</strong>t <strong>the</strong> multiples <strong>of</strong> three that are less<br />

than or equal to 20. At each iteration <strong>of</strong> <strong>the</strong> while loop, <strong>Matlab</strong> checks to see if k<br />

is divisible by 3. If not, it <strong>in</strong>crements <strong>the</strong> counter k, <strong>the</strong>n <strong>the</strong> cont<strong>in</strong>ue statment

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

Saved successfully!

Ooh no, something went wrong!