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
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
306 <strong>Chapter</strong> 4 <strong>Programm<strong>in</strong>g</strong> <strong>in</strong> <strong>Matlab</strong><br />
Enter a number a: 15.637<br />
Enter a number b: 28.4<br />
1) Add a and b.<br />
2) Subtract b from a.<br />
3) Multiply a and b.<br />
4) Divide a by b.<br />
Enter your choice: 5<br />
Not a valid choice.<br />
Loops<br />
A for loop is a control structure that is designed to execute a block <strong>of</strong> statements<br />
a predeterm<strong>in</strong>ed number <strong>of</strong> times. Here is its general use syntax.<br />
for <strong>in</strong>dex=start:<strong>in</strong>crement:f<strong>in</strong>ish<br />
statements<br />
end<br />
As an example, we display <strong>the</strong> squares <strong>of</strong> every o<strong>the</strong>r <strong>in</strong>teger from 5 to 13, <strong>in</strong>clusive.<br />
for k=5:2:13<br />
fpr<strong>in</strong>tf(’The square <strong>of</strong> %d is %d.\n’, k, k^2)<br />
end<br />
The output <strong>of</strong> this simple loop follows.<br />
The square <strong>of</strong> 5 is 25.<br />
The square <strong>of</strong> 7 is 49.<br />
The square <strong>of</strong> 9 is 81.<br />
The square <strong>of</strong> 11 is 121.<br />
The square <strong>of</strong> 13 is 169.<br />
Ano<strong>the</strong>r loop<strong>in</strong>g construct is <strong>Matlab</strong>’s while structure who’s basic syntax follows.