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

if n==1<br />

fpr<strong>in</strong>tf(’The sum <strong>of</strong> %0.2f and %0.2f is %0.2f.\n’,a,b,a+b)<br />

elseif n==2<br />

fpr<strong>in</strong>tf(’The difference <strong>of</strong> %0.2f and %.2f is %.2f.\n’,a,b,a-b)<br />

elseif n==3<br />

fpr<strong>in</strong>tf(’The product <strong>of</strong> %.2f and %.2f is %.2f.\n’,a,b,a*b)<br />

elseif n==4<br />

fpr<strong>in</strong>tf(’The quotient <strong>of</strong> %.2f and %.2f is %.2f.\n’,a,b,a/b)<br />

else<br />

fpr<strong>in</strong>tf(’Not a valid choice.\n’)<br />

end<br />

Save this script as mymenu.m, <strong>the</strong>n execute <strong>the</strong> command mymenu at <strong>the</strong><br />

command w<strong>in</strong>dow prompt. You will be prompted to enter two numbers a and b.<br />

As shown, we entered 15.637 for a and 28.4 for b. The program presents a menu<br />

<strong>of</strong> choices and prompts us for a choice.<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:<br />

We enter 1 as our choice and <strong>the</strong> program responds by add<strong>in</strong>g <strong>the</strong> values <strong>of</strong> a and<br />

b.<br />

Enter your choice: 1<br />

The sum <strong>of</strong> 15.64 and 28.40 is 44.04.<br />

Some comments are <strong>in</strong> order.<br />

1. Note that after several elseif statments, we still list an else command to catch<br />

<strong>in</strong>valid entries for n. The choice for n should match a menu designation, ei<strong>the</strong>r<br />

1, 2, 3, or 4, but any o<strong>the</strong>r choice for n causes <strong>the</strong> statement follow<strong>in</strong>g else to

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

Saved successfully!

Ooh no, something went wrong!