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> 311<br />

The actual value <strong>of</strong> pi^2/6 is 1.644934.<br />

The sum <strong>of</strong> <strong>the</strong> first 1216 terms is 1.644112.<br />

The relative error is 0.000500.<br />

Note that we have agreement <strong>in</strong> approximately 4 significant digits.<br />

This example demonstrates when we should use a for loop and when a while<br />

loop is more appropriate. We <strong>of</strong>fer <strong>the</strong> follow<strong>in</strong>g advice.<br />

What type <strong>of</strong> loop should I use? When you know <strong>in</strong> advance <strong>the</strong> precise<br />

number <strong>of</strong> times <strong>the</strong> loop should <strong>in</strong>terate, use a for loop. On <strong>the</strong> o<strong>the</strong>r hand,<br />

if you have no predeterm<strong>in</strong>ed knowledge <strong>of</strong> how many times you will need<br />

<strong>the</strong> loop to execute, use a while loop.<br />

For k = A<br />

<strong>Matlab</strong> also supports a type <strong>of</strong> for loop whose block <strong>of</strong> statements are executed<br />

for each column <strong>in</strong> a matrix A. The syntax is as follows.<br />

for k = A<br />

statements<br />

end<br />

In this construct, <strong>the</strong> columns <strong>of</strong> matrix A are stored one at a time <strong>in</strong> <strong>the</strong> variable<br />

k while <strong>the</strong> follow<strong>in</strong>g statments, up to <strong>the</strong> end, are executed. For example, enter<br />

<strong>the</strong> matrix A.<br />

>> A=[1 2;3 4]<br />

A =<br />

1 2<br />

3 4<br />

Now, enter and exercute <strong>the</strong> follow<strong>in</strong>g loop.

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

Saved successfully!

Ooh no, something went wrong!