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.

388 <strong>Chapter</strong> 4 <strong>Programm<strong>in</strong>g</strong> <strong>in</strong> <strong>Matlab</strong><br />

Next, add <strong>the</strong> follow<strong>in</strong>g l<strong>in</strong>es at <strong>the</strong> very bottom <strong>of</strong> <strong>the</strong> file rationalArithmetic.m.<br />

function d=rationalGCD(a,b)<br />

while true<br />

a=mod(a,b);<br />

if a==0<br />

d=b;<br />

return<br />

end<br />

b=mod(b,a);<br />

if b==0<br />

d=a;<br />

return<br />

end<br />

end<br />

Actually, <strong>the</strong> order <strong>of</strong> <strong>the</strong> subfunctions is irrelevant, but collect<strong>in</strong>g <strong>the</strong>m at <strong>the</strong><br />

bottom <strong>of</strong> <strong>the</strong> primary function M-file rationalArithmetic.m is a good practice,<br />

mak<strong>in</strong>g <strong>the</strong>m easy to f<strong>in</strong>d and separat<strong>in</strong>g <strong>the</strong>m from <strong>the</strong> ma<strong>in</strong> body <strong>of</strong> code.<br />

However, <strong>the</strong> order <strong>in</strong> which <strong>the</strong>y appear at <strong>the</strong> bottom <strong>of</strong> <strong>the</strong> primary function<br />

file rationalArithmetic.m makes no difference to execution.<br />

Activat<strong>in</strong>g Menu Items. We now need to write some code so that when <strong>the</strong><br />

user selects <strong>the</strong> first menu item (Reduce a fraction to lowest terms), two th<strong>in</strong>gs<br />

will happen:<br />

1. The user will be asked to <strong>in</strong>put <strong>the</strong> numerator and denom<strong>in</strong>ator <strong>of</strong> <strong>the</strong> fraction<br />

she wants reduced.<br />

2. The program will output an equivalent fraction that is reduced to lowest terms.<br />

With <strong>the</strong>se thoughts <strong>in</strong> m<strong>in</strong>d, add <strong>the</strong>se l<strong>in</strong>es to rationalArithmetic.m just<br />

after case 1.

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

Saved successfully!

Ooh no, something went wrong!