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

if logical_expression<br />

statements<br />

else<br />

statments<br />

end<br />

In this form, if <strong>the</strong> logical_expression evaluates as true (logical 1), <strong>the</strong> block<br />

<strong>of</strong> statements between if and else are executed. If <strong>the</strong> logical_expression<br />

evaluates as false (logical 0), <strong>the</strong>n <strong>the</strong> block <strong>of</strong> statements between else and end<br />

are executed.<br />

We can provide an alternative to our evenodd.m script. Add <strong>the</strong> follow<strong>in</strong>g<br />

l<strong>in</strong>es to <strong>the</strong> script and resave as evenodd.m.<br />

n = <strong>in</strong>put(’Enter an <strong>in</strong>teger: ’);<br />

if (rem(n,2)==0)<br />

fpr<strong>in</strong>tf(’The <strong>in</strong>teger %d is even.\n’, n)<br />

else<br />

fpr<strong>in</strong>tf(’The <strong>in</strong>teger %d is odd.\n’, n)<br />

end<br />

Run <strong>the</strong> program, enter 17, and note that we now have a different response.<br />

>> evenodd<br />

Enter an <strong>in</strong>teger: 17<br />

The <strong>in</strong>teger 17 is odd.<br />

Because <strong>the</strong> logical expression rem(n,2)==0 evaluates as false when n = 17,<br />

<strong>the</strong> fpr<strong>in</strong>tf command that lies between else and end is executed, <strong>in</strong>form<strong>in</strong>g us<br />

that <strong>the</strong> <strong>in</strong>put is an odd <strong>in</strong>teger.<br />

Elseif<br />

Sometimes we need to add more than one alternative.<br />

follow<strong>in</strong>g structure.<br />

For this, we have <strong>the</strong>

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

Saved successfully!

Ooh no, something went wrong!