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.

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

n=5;<br />

H=zeros(n);<br />

Now, doubly nested for loops achieve <strong>the</strong> desired result.<br />

for i=1:n<br />

for j=1:n<br />

H(i,j)=1/(i+j-1);<br />

end<br />

end<br />

Set rational display format, display <strong>the</strong> matrix H, <strong>the</strong>n set <strong>the</strong> format back to<br />

default.<br />

format rat<br />

H<br />

format<br />

The result is shown <strong>in</strong> <strong>the</strong> follow<strong>in</strong>g Hilbert Matrix <strong>of</strong> order 5.<br />

H =<br />

1 1/2 1/3 1/4 1/5<br />

1/2 1/3 1/4 1/5 1/6<br />

1/3 1/4 1/5 1/6 1/7<br />

1/4 1/5 1/6 1/7 1/8<br />

1/5 1/6 1/7 1/8 1/9<br />

Note that <strong>the</strong> entry is row 3 column 2 is 1/4, as predicted by our hand calculations<br />

above. Similar hand calculations can be used to verify o<strong>the</strong>r entries <strong>in</strong> this result.<br />

How does it work? Because n = 5, <strong>the</strong> primary loop becomes for i=1:5.<br />

Similarly, <strong>the</strong> <strong>in</strong>ner loop becomes for j=1:5. Now, here is <strong>the</strong> way <strong>the</strong> nested<br />

structure proceeds. First, set i = 1, <strong>the</strong>n execute <strong>the</strong> statement H(i,j)=1/(i+j-<br />

1) for j = 1, 2, 3, 4, and 5. With this first pass, we set <strong>the</strong> entries H(1, 1), H(1, 2),<br />

H(1, 3), H(1, 4), and H(1, 5). The <strong>in</strong>ner loop term<strong>in</strong>ates and control returns to<br />

<strong>the</strong> primary loop, where <strong>the</strong> program next sets i = 2 and aga<strong>in</strong> executes <strong>the</strong><br />

statement H(i,j)=1/(i+j-1) for j = 1, 2, 3, 4, and 5. With this second pass, we<br />

set <strong>the</strong> entries H(2, 1), H(2, 2), H(2, 3), H(2, 4), and H(2, 5). A third and fourth

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

Saved successfully!

Ooh no, something went wrong!