Professional Documents
Culture Documents
Exercises
1)Whatwouldbetheresultofthefollowingexpressions?
' b' >= ' c' 1 1
3 == 2 + 1 1
( 3 == 2) + 1 1
xor ( 5 < 6, 8 > 4) 0
2)Writeascriptthattestswhethertheusercanfollowinstructions.Itpromptsthe
usertoenteranx.Iftheuserentersanythingotherthananx,itprintsanerror
messageotherwise,thescriptdoesnothing.
Ch3Ex2.m
%Can t he user f ol l ow i nst r uct i ons??
i nx = i nput ( ' Ent er an x: ' , ' s' ) ;
i f i nx ~= ' x'
f pr i nt f ( ' That was no x! \ n' )
end
3)Writeafunctionnexthourthatreceivesoneintegerargument,whichisanhourof
theday,andreturnsthenexthour.Thisassumesa12hourclock;so,forexample,
thenexthourafter12wouldbe1.Herearetwoexamplesofcallingthisfunction.
>> fprintf('The next hour will be %d.\n',nexthour(3))
The next hour wi l l be 4.
>> fprintf('The next hour will be %d.\n',nexthour(12))
The next hour wi l l be 1.
nexthour.m
f unct i on out hour = next hour ( cur r ent hour )
%Recei ves an i nt eger hour of t he day and
%r et ur ns t he next i nt eger hour
%For mat of cal l : next hour ( hour of day)
%Ret ur ns t he next i nt eger hour
out hour = cur r ent hour + 1;
i f out hour == 13
out hour = 1;
end
end
4) Write a script to calculate the volume of a pyramid, which is 1/3 * base * height,
where the base is length * width. Prompt the user to enter values for the length, width,
and height, and then calculate the volume of the pyramid. When the user enters each
value, he or she will then also be prompted for either i for inches or c for centimeters.
(Note 2.54 cm =1 inch). The script should print the volume in cubic inches with three
decimal places. As an example, the output format will be:
Thi s pr ogr amwi l l cal cul at e t he vol ume of a pyr ami d.
Ent er t he l engt h of t he base: 50
I s t hat i or c? i
Ent er t he wi dt h of t he base: 6
I s t hat i or c? c
Ent er t he hei ght : 4
I s t hat i or c? i
The vol ume of t he pyr ami d i s xxx. xxx cubi c i nches.
Ch3Ex4.m
%Cal cul at e t he vol ume of a pyr ami d
%Pr ompt t he user f or t he l engt h, wi dt h, and hei ght i n
%ei t her i nches or cent i met er s ( i nches i s assumed and
wi l l
%be t he def aul t )
di sp( ' Thi s scr i pt wi l l cal cul at e t he vol ume of a
pyr ami d. ' )
l en = i nput ( ' Ent er t he l engt h of t he base: ' ) ;
l enuni t = i nput ( ' I s t hat i or c? ' , ' s' ) ;
i f l enuni t == ' c'
l en = l en/ 2. 54;
end
wi d = i nput ( ' Ent er t he wi dt h of t he base: ' ) ;
wi duni t = i nput ( ' I s t hat i or c? ' , ' s' ) ;
i f wi duni t == ' c'
wi d = wi d/ 2. 54;
end
ht = i nput ( ' Ent er t he hei ght : ' ) ;
ht uni t = i nput ( ' I s t hat i or c? ' , ' s' ) ;
i f ht uni t == ' c'
ht = ht / 2. 54;
end
vol = 1/ 3 * l en * wi d * ht ;
f pr i nt f ( ' \ nThe vol ume of t he pyr ami d i s ' )
f pr i nt f ( ' %. 3f cubi c i nches. \ n' , vol )
5)Writeascripttoprompttheuserforacharacter,andthenprintetherthatitisa
letterofthealphabetorthatitisnot.
Ch3Ex5. m
%Pr ompt f or a char act er and pr i nt whet her i t i s
%a l et t er of t he al phabet or not
l et = i nput ( ' Ent er a char act er : ' , ' s' ) ;
i f ( l et >= ' a' && l et <= ' z' ) | | . . .
( l et >= ' A' && l et <= ' Z' )
f pr i nt f ( ' %c i s a l et t er \ n' , l et )
el se
f pr i nt f ( ' %c i s not a l et t er \ n' , l et )
end
6)Writeascriptthatwillprompttheuserforanumeratorandadenominatorfora
fraction.Ifthedenominatoris0,itwillprintanerrormessagesayingthatdivision
by0isnotpossible.Ifthedenominatorisnot0,itwillprinttheresultofthe
fraction.
Ch3Ex6. m
%Pr ompt t he user f or a numer at or and denomi nat or
%and pr i nt t he f r act i on or an er r or message
num= i nput ( ' Ent er t he numer at or : ' ) ;
den = i nput ( ' Ent er t he denomi nat or : ' ) ;
i f den == 0
f pr i nt f ( ' Di vi si on by 0 not possi bl e\ n' )
el se
f pr i nt f ( ' The f r act i on i s %. 2f \ n' , num/ den)
end
7)Theeccentricityofanellipseisdefinedas
|
.
|
\
|
a
b
2
1
whereaisthesemimajoraxisandbisthesemiminoraxisoftheellipse.Ascript
promptstheuserforthevaluesofaandb.Sincedivisionby0isnotpossible,the
scriptprintsanerrormessageifthevalueofais0(itignoresanyothererrors,
however).Ifaisnot0,thescriptcallsafunctiontocalculateandreturnthe
eccentricity,andthenthescriptprintstheresult.Writethescriptandthefunction.
Ch3Ex7. m
%Pr ompt s t he user f or t he semi maj or and semi mi nor axes of
%an el l i pse and cal cul at es and r et ur ns t he eccent r i ci t y
%( i f t he semi maj or axi s ~=0)
a = i nput ( ' Ent er t he semi maj or axi s: ' ) ;
b = i nput ( ' Ent er t he semi mi nor axi s: ' ) ;
i f a == 0
di sp( ' Er r or : semi maj or cannot be 0' )
el se
eccent r i ci t y = El l Ecc( a, b) ;
f pr i nt f ( ' The eccent r i ci t y i s %. 2f \ n' , eccent r i ci t y)
end
El l Ecc. m
f unct i on eccen = El l Ecc( a, b)
%Cal cul at es t he eccent r i ci t y of an el l i pse gi ven
%t he semi maj or axi s a and t he semi mi nor axi s b
%For mat of cal l : El l Ecc( a, b)
%Ret ur ns t he eccent r i ci t y
eccen = sqr t ( 1- ( b/ a) ^2) ;
end
8)Thesystolicanddiastolicbloodpressurereadingsarefoundwhentheheartis
pumpingandtheheartisatrest,respectively.Abiomedicalexperimentisbeing
conductedonlyonsubjectswhosebloodpressureisoptimal.Thisisdefinedasa
systolicbloodpressurelessthan120andadiastolicbloodpressurelessthan80.
Writeascriptthatwillpromptforthesystolicanddiastolicbloodpressuresofa
person,andwillprintwhetherornotthatpersonisacandidateforthisexperiment.
Ch3Ex8.m
%Checks bl ood pr essur es t o det er mi ne whet her or
%not a per son i s a candi dat e f or an exper i ment
syst = i nput ( ' Ent er t he syst ol i c bl ood pr essur e: ' ) ;
di ast = i nput ( ' Ent er t he di ast ol i c bl ood pr essur e: ' ) ;
i f syst < 120 && di ast < 80
di sp( ' Thi s per son i s a candi dat e. ' )
el se
di sp( ' Thi s per son i s not sui t abl e f or t he exper i ment . ' )
end
9)Thecontinuityequationinfluiddynamicsforsteadyfluidflowthroughastream
tubeequatestheproductofthedensity,velocity,andareaattwopointsthathave
varyingcrosssectionalareas.Forincompressibleflow,thedensitiesareconstantso
theequationisA
1
V
1
=A
2
V
2
.IftheareasandV
1
areknown,V
2
canbefoundas
1
2
1
V
A
A
.
Therefore,whetherthevelocityatthesecondpointincreasesordecreasesdepends
ontheareasatthetwopoints.Writeascriptthatwillprompttheuserforthetwo
areasinsquarefeet,andwillprintwhetherthevelocityatthesecondpointwill
increase,decrease,orremainthesameasatthefirstpoint.
Ch3Ex9.m
%Pr i nt s whet her t he vel oci t y at a poi nt i n a st r eamt ube
%wi l l i ncr ease, decr ease, or r emai n t he same at a second
%poi nt based on t he cr oss- sect i onal ar eas of t wo poi nt s
a1 = i nput ( ' Ent er t he ar ea at poi nt 1: ' ) ;
a2 = i nput ( ' Ent er t he ar ea at poi nt 2: ' ) ;
i f a1 > a2
di sp( ' The vel oci t y wi l l i ncr ease' )
el sei f a1 < a2
di sp( ' The vel oci t y wi l l decr ease' )
el se
di sp( ' The vel oci t y wi l l r emai n t he same' )
end
10)Inchemistry,thepHofanaqueoussolutionisameasureofitsacidity.ThepH
scalerangesfrom0to14,inclusive.AsolutionwithapHof7issaidtobeneutral,a
solutionwithapHgreaterthan7isbasic,andasolutionwithapHlessthan7is
acidic.WriteascriptthatwillprompttheuserforthepHofasolution,andwill
printwhetheritisneutral,basic,oracidic.IftheuserentersaninvalidpH,anerror
messagewillbeprinted.
Ch3Ex10.m
%Pr ompt s t he user f or t he pH of a sol ut i on and pr i nt s
%whet her i t i s basi c, aci di c, or neut r al
ph = i nput ( ' Ent er t he pH of t he sol ut i on: ' ) ;
i f ph >=0 && ph <= 14
i f ph < 7
di sp( ' I t i s aci di c' )
el sei f ph == 7
di sp( ' I t i s neut r al ' )
el sei f ph > 7
di sp( ' I t i s basi c' )
end
el se
di sp( ' Er r or i n pH! ' )
end
11)WriteafunctioncreatevecMToNthatwillcreateandreturnavectorofintegers
frommton(wheremisthefirstinputargumentandnisthesecond),regardlessof
whethermislessthannorgreaterthann.Ifmisequalton,thevectorwilljustbe
1x1orascalar.
cr eat evecMToN. m
f unct i on out vec = cr eat evecMToN( m, n)
%Cr eat es a vect or of i nt eger s f r ommt o n
%For mat of cal l : cr eat evecMToN( m, n)
%Ret ur ns vect or of i nt eger s f r omm: n or m: - 1: n
i f m< n
out vec = m: n;
el se
out vec = m: - 1: n;
end
end
12)Writeafunctionflipvecthatwillreceiveoneinputargument.Iftheinput
argumentisarowvector,thefunctionwillreversetheorderandreturnanewrow
vector.Iftheinputargumentisacolumnvector,thefunctionwillreversetheorder
andreturnanewcolumnvector.Iftheinputargumentisamatrixorascalar,the
functionwillreturntheinputargumentunchanged.
f l i pvec. m
f unct i on out = f l i pvec( vec)
%Fl i ps i t i f i t ' s a vect or , ot her wi se
%r et ur ns t he i nput ar gument unchanged
%For mat of cal l : f l i pvec( vec)
%Ret ur ns f l i pped vect or or unchanged
[ r c] = si ze( vec) ;
i f r == 1 && c > 1
out = f l i pl r ( vec) ;
el sei f c == 1 && r > 1
out = f l i pud( vec) ;
el se
out = vec;
end
end
13)Inascript,theuserissupposedtoentereitherayorninresponsetoa
prompt.Theusersinputisreadintoacharactervariablecalledletter.Thescript
willprintOK,continuingiftheuserenterseitherayorYoritwillprintOK,
haltingiftheuserentersanorNorErroriftheuserentersanythingelse.Put
thisstatementinthescriptfirst:
l et t er = i nput ( ' Ent er your answer : ' , ' s' ) ;
Writethescriptusingasinglenestedifelsestatement(elseifclauseispermitted).
Ch3Ex13.m
%Pr ompt s t he user f or a ' y' or ' n' answer and r esponds
%accor di ngl y, usi ng an i f - el se st at ement
l et t er = i nput ( ' Ent er your answer : ' , ' s' ) ;
i f l et t er == ' y' | | l et t er == ' Y'
di sp( ' OK, cont i nui ng' )
el sei f l et t er == ' n' | | l et t er == ' N'
di sp( ' OK, hal t i ng' )
el se
di sp( ' Er r or ' )
end
14)Writethescriptfromthepreviousexerciseusingaswitchstatementinstead.
Ch3Ex14.m
%Pr ompt s t he user f or a ' y' or ' n' answer and r esponds
%accor di ngl y, usi ng an i f - el se st at ement
l et t er = i nput ( ' Ent er your answer : ' , ' s' ) ;
swi t ch l et t er
case {' y' , ' Y' }
di sp( ' OK, cont i nui ng' )
case {' n' , ' N' }
di sp( ' OK, hal t i ng' )
ot her wi se
di sp( ' Er r or ' )
end
15)Inaerodynamics,theMachnumberisacriticalquantity.Itisdefinedasthe
ratioofthespeedofanobject(e.g.,anaircraft)tothespeedofsound.IftheMach
numberislessthan1,theflowissubsonic;iftheMachnumberisequalto1,theflow
istransonic;iftheMachnumberisgreaterthan1,theflowissupersonic.Writea
scriptthatwillprompttheuserforthespeedofanaircraftandthespeedofsoundat
theaircraftscurrentaltitudeandwillprintwhethertheconditionissubsonic,
transonic,orsupersonic.
Ch3Ex15.m
%Pr i nt s whet her t he speed of an obj ect i s subsoni c,
%t r ansoni c, or super soni c based on t he Mach number
pl ane_speed = i nput ( ' Ent er t he speed of t he ai r cr af t : ' ) ;
sound_speed = i nput ( ' Ent er t he speed of sound: ' ) ;
mach = pl ane_speed/ sound_speed;
i f mach < 1
di sp( ' Subsoni c' )
el sei f mach == 1
di sp( ' Tr ansoni c' )
el se
di sp( ' Super soni c' )
end
16)WriteascriptthatwillprompttheuserforatemperatureindegreesCelsius,
andthenanFforFahrenheitorKforKelvin.Thescriptwillprintthe
correspondingtemperatureinthescalespecifiedbytheuser.Forexample,the
outputmightlooklikethis:
Ent er t he t emp i n degr ees C: 29. 3
Do you want K or F? F
The t emp i n degr ees F i s 84. 7
Theformatoftheoutputshouldbeexactlyasspecifiedabove.Theconversionsare:
32 C
5
9
F + =
273.15 C K + =
Ch3Ex16.m
%Conver t s a t emper at ur e f r omC t o F or K
cel = i nput ( ' Ent er t he t emp i n degr ees C: ' ) ;
f or k = i nput ( ' Do you want F or K? ' , ' s' ) ;
i f f or k == ' F' | | f or k == ' f '
f pr i nt f ( ' The t emp i n degr ees F i s %. 1f \ n' , 9/ 5*cel +32)
el se
f pr i nt f ( ' The t emp i n degr ees K i s %. 1f \ n' , cel +273. 15)
end
17)Writeascriptthatwillgenerateonerandominteger,andwillprintwhetherthe
randomintegerisanevenoranoddnumber.(Hint:anevennumberisdivisibleby
2,whereasanoddnumberisnot;sochecktheremainderafterdividingby2.)
Ch3Ex17.m
%Gener at es a r andomi nt eger and pr i nt s whet her i t i s even
or odd
r anI nt = r andi ( [ 1, 100] ) ;
i f r em( r anI nt , 2) == 0
f pr i nt f ( ' %d i s even\ n' , r anI nt )
el se
f pr i nt f ( ' %d i s odd\ n' , r anI nt )
end
18)Writeafunctionisdivby4thatwillreceiveanintegerinputargument,andwill
returnlogical1fortrueiftheinputargumentisdivisibleby4,orlogicalfalseifit
isnot.
isdivby4.m
f unct i on out = i sdi vby4( i nar g)
%Ret ur ns 1 f or t r ue i f t he i nput ar gument i s
% di vi si bl e by 4 or 0 f or f al se i f not
%For mat of cal l : i sdi vby4( i nput ar g)
%Ret ur ns whet her di vi si bl e by 4 or not
out = r em( i nar g, 4) == 0;
end
19)Writeafunctionisintthatwillreceiveanumberinputargumentinnum,andwill
return1fortrueifthisnumberisaninteger,or0forfalseifnot.Usethefactthat
innumshouldbeequaltoint32(innum)ifitisaninteger.Unfortunately,dueto
roundofferrors,itshouldbenotedthatitispossibletogetlogical1fortrueifthe
inputargumentisclosetoaninteger.Thereforetheoutputmaynotbewhatyou
mightexpect,asshownhere.
>> isint(4)
ans =
1
>> isint(4.9999)
ans =
0
>> isint(4.9999999999999999999999999999)
ans =
1
i si nt . m
f unct i on out = i si nt ( i nnum)
%Ret ur ns 1 f or t r ue i f t he ar gument i s an i nt eger
%For mat of cal l : i si nt ( number )
%Ret ur ns l ogi cal 1 i f f number i s an i nt eger
out = i nnum== i nt 32( i nnum) ;
end
20)APythagoreantripleisasetofpositiveintegers(a,b,c)suchthata
2
+b
2
=c
2
.
Writeafunctionispythagthatwillreceivethreepositiveintegers(a,b,cinthat
order)andwillreturnlogical1fortrueiftheyformaPythagoreantriple,or0for
falseifnot.
ispythag.m
f unct i on out = i spyt hag( a, b, c)
%Det er mi nes whet her a, b, c ar e a Pyt hagor ean
% t r i pl e or not
%For mat of cal l : i spyt hag( a, b, c)
%Ret ur ns l ogi cal 1 i f a Pyt hagor ean t r i pl e
out = a^2 + b^2 == c^2;
end
21)Influiddynamics,theReynoldsnumberReisadimensionlessnumberusedto
determinethenatureofafluidflow.Foraninternalflow(e.g.,waterflowthrougha
pipe),theflowcanbecategorizedasfollows:
Re2300 LaminarRegion
2300<Re4000 TransitionRegion
Re>4000 TurbulentRegion
WriteascriptthatwillprompttheuserfortheReynoldsnumberofaflowandwill
printtheregiontheflowisin.Hereisanexampleofrunningthescript:
>> Reynolds
Ent er a Reynol ds number : 3500
The f l ow i s i n t r ansi t i on r egi on
Ch3Ex21. m
%Pr ompt s t he user f or t he Reynol ds number
%f or an i nt er nal f l ow and pr i nt s
%whet her i t i s l ami nar , t ur bul ent , or i n
%a t r ansi t i on r egi on
Re = i nput ( ' Ent er a Reynol ds number : ' ) ;
i f Re <= 2300
di sp( ' The f l ow i s i n l ami nar r egi on' )
el sei f Re > 2300 && Re <= 4000
di sp( ' The f l ow i s i n t r ansi t i on r egi on' )
el se
di sp( ' The f l ow i s i n t ur bul ent r egi on' )
end
Woulditbeagoodideatowritetheselectionstatementsusingswitch?Whyorwhy
not?
No,becausetheReynoldsnumbercouldbearealnumberandtherangesaretoo
large.
22)TheareaAofarhombusisdefinedasA=
2
2 1
d d
,whered
1
andd
2
arethelengths
ofthetwodiagonals.Writeascriptrhombthatfirstpromptstheuserforthelengths
ofthetwodiagonals.Ifeitherisanegativenumberorzero,thescriptprintsan
errormessage.Otherwise,iftheyarebothpositive,itcallsafunctionrhombareato
returntheareaoftherhombus,andprintstheresult.Writethefunction,also!The
lengthsofthediagonals,whichyoucanassumeareininches,arepassedtothe
rhombareafunction.
rhomb.m
%Pr ompt t he user f or t he t wo di agonal s of a r hombus,
%cal l a f unct i on t o cal cul at e t he ar ea, and pr i nt i t
d1 = i nput ( ' Ent er t he f i r st di agonal : ' ) ;
d2 = i nput ( ' Ent er t he second di agonal : ' ) ;
i f d1 <= 0 | | d2 <= 0
di sp( ' Er r or i n di agonal ' )
el se
r har ea = r hombar ea( d1, d2) ;
f pr i nt f ( ' The ar ea of t he r hombus i s %. 2f \ n' , r har ea)
end
rhombarea.m
f unct i on r ar ea = r hombar ea( d1, d2)
%Cal cul at es t he ar ea of a r hombus gi ven t he
%l engt hs of t he t wo di agonal s
%For mat of cal l : r hombar ea( di ag1, di ag2)
%Ret ur ns t he ar ea of t he r hombus
r ar ea = ( d1*d2) / 2;
end
Globaltemperaturechangeshaveresultedinnewpatternsofstormsinmanypartsof
theworld.Trackingwindspeedsandavarietyofcategoriesofstormsisimportantin
understandingtheramificationsofthesetemperaturevariations.Programsthatwork
withstormdatawilluseselectionstatementstodeterminetheseverityofstormsand
alsotomakedecisionsbasedonthedata.
23)Whetherastormisatropicaldepression,tropicalstorm,orhurricaneis
determinedbytheaveragesustainedwindspeed.Inmilesperhour,astormisa
tropicaldepressionifthewindsarelessthan38mph.Itisatropicalstormifthe
windsarebetween39and73mph,anditisahurricaneifthewindspeedsare>=74
mph.Writeascriptthatwillprompttheuserforthewindspeedofthestorm,and
willprintwhichtypeofstormitis.
Ch3Ex23.m
%Pr i nt s whet her a st or mi s a t r opi cal depr essi on, t r opi cal
%st or m, or hur r i cane based on wi nd speed
wi nd = i nput ( ' Ent er t he wi nd speed of t he st or m: ' ) ;
i f wi nd < 38
di sp( ' Tr opi cal depr essi on' )
el sei f wi nd >= 38 && wi nd < 73
di sp( ' Tr opi cal st or m' )
el se
di sp( ' Hur r i cane' )
end
24)Hurricanesarecategorizedbasedonwindspeeds.Thefollowingtableshows
theCategorynumberforhurricaneswithvaryingwindrangesandwhatthestorm
surgeis(infeetabovenormal).
Ch3Ex24.m
%Pr i nt s t he cat egor y number and st or msur ge f or
%a hur r i cane based on t he wi nd speed
wi nd = i nput ( ' Ent er t he wi nd speed: ' ) ;
i f wi nd >= 74 && wi nd <=95
f pr i nt f ( ' Cat egor y 1; t ypi cal st or msur ge 4- 5 f t \ n' )
el sei f wi nd > 95 && wi nd <= 110
f pr i nt f ( ' Cat egor y 2; t ypi cal st or msur ge 6- 8 f t \ n' )
el sei f wi nd > 110 && wi nd <= 130
f pr i nt f ( ' Cat egor y 3; t ypi cal st or msur ge 9- 12 f t \ n' )
el sei f wi nd > 130 && wi nd <= 155
f pr i nt f ( ' Cat egor y 4; t ypi cal st or msur ge 13- 18 f t \ n' )
el sei f wi nd > 155
f pr i nt f ( ' Cat egor y 5; t ypi cal st or msur ge > 18 f t \ n' )
el se
f pr i nt f ( ' Not a hur r i cane\ n' )
end
25)TheBeaufortWindScaleisusedtocharacterizethestrengthofwinds.Thescale
usesintegervaluesandgoesfromaforceof0,whichisnowind,upto12,whichisa
hurricane.Thefollowingscriptfirstgeneratesarandomforcevalue.Then,itprints
amessageregardingwhattypeofwindthatforcerepresents,usingaswitch
statement.Youaretorewritethisswitchstatementasonenestedifelse
statementthataccomplishesexactlythesamething.Youmayuseelseand/orelseif
clauses.
Ch3Ex25.m
i f r anf or ce == 0
di sp( ' Ther e i s no wi nd' )
el sei f r anf or ce >= 1 && r anf or ce <= 6
di sp( ' Ther e i s a br eeze' )
el sei f r anf or ce >= 7 && r anf or ce <= 9
di sp( ' Thi s i s a gal e' )
el sei f r anf or ce == 10 | | r anf or ce == 11
di sp( ' I t i s a st or m' )
el se
di sp( ' Hel l o, Hur r i cane! ' )
end
26)Cloudsaregenerallyclassifiedashigh,middle,orlowlevel.Theheightofthe
cloudisthedeterminingfactor,buttherangesvarydependingonthetemperature.
Forexample,intropicalregionstheclassificationsmaybebasedonthefollowing
heightranges(giveninfeet):
low 06500
middle 650020000
high >20000
Writeascriptthatwillprompttheuserfortheheightofthecloudinfeet,andprint
theclassification.
Ch3Ex26.m
%Pr i nt s cl oud cl assi f i cat i on
cl oudHt = i nput ( ' Ent er t he hei ght of t he cl oud i n f eet : ' ) ;
i f cl oudHt > 0 && cl oudHt <=6500
di sp( ' Thi s i s a l ow cl oud' )
el sei f cl oudHt > 6500 && cl oudHt <= 20000
di sp( ' Thi s i s a mi ddl e cl oud' )
el sei f cl oudHt > 20000
di sp( ' Thi s i s a hi gh cl oud' )
el se
di sp( ' Er r or : how coul d t hi s be a cl oud?' )
end
27)Rewritethefollowingswitchstatementasonenestedifelsestatement(elseif
clausesmaybeused).Assumethatthereisavariableletterandthatithasbeen
initialized.
swi t ch l et t er
case ' x'
di sp( ' Hel l o' )
case {' y' , ' Y' }
di sp( ' Yes' )
case ' Q'
di sp( ' Qui t ' )
ot her wi se
di sp( ' Er r or ' )
end
Ch3Ex27.m
l et t er = char ( r andi ( [ 97, 122] ) ) ;
i f l et t er == ' x'
di sp( ' Hel l o' )
el sei f l et t er == ' y' | | l et t er == ' Y'
di sp( ' Yes' )
el sei f l et t er == ' Q'
di sp( ' Qui t ' )
el se
di sp( ' Er r or ' )
end
28)Rewritethefollowingnestedifelsestatementasaswitchstatementthat
accomplishesexactlythesamething.Assumethatnumisanintegervariablethat
hasbeeninitialized,andthattherearefunctionsf1,f2,f3,andf4.Donotuseanyif
orifelsestatementsintheactionsintheswitchstatement,onlycallstothefour
functions.
i f num< - 2 | | num> 4
f 1( num)
el se
i f num<= 2
i f num>= 0
f 2( num)
el se
f 3( num)
end
el se
f 4( num)
end
end
Ch3Ex28.m
swi t ch num
case {- 2, - 1}
f 3( num)
case {0, 1, 2}
f 2( num)
case {3, 4}
f 4( num)
ot her wi se
f 1( num)
end
29)WriteascriptareaMenuthatwillprintalistconsistingofcylinder,circle,and
rectangle.Itpromptstheusertochooseone,andthenpromptstheuserforthe
appropriatequantities(e.g.,theradiusofthecircle)andthenprintsitsarea.Ifthe
userentersaninvalidchoice,thescriptsimplyprintsanerrormessage.Thescript
shoulduseanestedifelsestatementtoaccomplishthis.Herearetwoexamplesof
runningit(unitsareassumedtobeinches).
>> areaMenu
Menu
1. Cyl i nder
2. Ci r cl e
3. Rect angl e
Pl ease choose one: 2
Ent er t he r adi us of t he ci r cl e: 4. 1
The ar ea i s 52. 81
>> areaMenu
Menu
1. Cyl i nder
2. Ci r cl e
3. Rect angl e
Pl ease choose one: 3
Ent er t he l engt h: 4
Ent er t he wi dt h: 6
The ar ea i s 24. 00
areaMenu.m
%Pr i nt s a menu and cal cul at es ar ea of user ' s choi ce
di sp( ' Menu' )
di sp( ' 1. Cyl i nder ' )
di sp( ' 2. Ci r cl e' )
di sp( ' 3. Rect angl e' )
sh = i nput ( ' Pl ease choose one: ' ) ;
i f sh == 1
r ad = i nput ( ' Ent er t he r adi us of t he cyl i nder : ' ) ;
ht = i nput ( ' Ent er t he hei ght of t he cyl i nder : ' ) ;
f pr i nt f ( ' The sur f ace ar ea i s %. 2f \ n' , 2*pi *r ad*ht )
el sei f sh == 2
r ad = i nput ( ' Ent er t he r adi us of t he ci r cl e: ' ) ;
f pr i nt f ( ' The ar ea i s %. 2f \ n' , pi *r ad*r ad)
el sei f sh == 3
l en = i nput ( ' Ent er t he l engt h: ' ) ;
wi d = i nput ( ' Ent er t he wi dt h: ' ) ;
f pr i nt f ( ' The ar ea i s %. 2f \ n' , l en*wi d)
el se
di sp( ' Er r or ! Not a val i d choi ce. ' )
end
30)ModifytheareaMenuscripttouseaswitchstatementtodecidewhichareato
calculate.
areaMenuSwitch.m
%Pr i nt s a menu and cal cul at es ar ea of user ' s choi ce
di sp( ' Menu' )
di sp( ' 1. Cyl i nder ' )
di sp( ' 2. Ci r cl e' )
di sp( ' 3. Rect angl e' )
sh = i nput ( ' Pl ease choose one: ' ) ;
swi t ch sh
case 1
r ad = i nput ( ' Ent er t he r adi us of t he cyl i nder : ' ) ;
ht = i nput ( ' Ent er t he hei ght of t he cyl i nder : ' ) ;
f pr i nt f ( ' The sur f ace ar ea i s %. 2f \ n' , 2*pi *r ad*ht )
case 2
r ad = i nput ( ' Ent er t he r adi us of t he ci r cl e: ' ) ;
f pr i nt f ( ' The ar ea i s %. 2f \ n' , pi *r ad*r ad)
case 3
l en = i nput ( ' Ent er t he l engt h: ' ) ;
wi d = i nput ( ' Ent er t he wi dt h: ' ) ;
f pr i nt f ( ' The ar ea i s %. 2f \ n' , l en*wi d)
ot her wi se
di sp( ' Er r or ! Not a val i d choi ce. ' )
end
31)ModifytheareaMenuscript(eitherversion)tousethebuiltinmenufunction
insteadofprintingthemenuchoices.
Ch3Ex31.m
%Pr i nt s a menu and cal cul at es ar ea of user ' s choi ce
sh = menu( ' Pl ease choose one: ' , ' Cyl i nder ' , ' Ci r cl e' , ' Rect angl e' ) ;
swi t ch sh
case 1
r ad = i nput ( ' Ent er t he r adi us of t he cyl i nder : ' ) ;
ht = i nput ( ' Ent er t he hei ght of t he cyl i nder : ' ) ;
f pr i nt f ( ' The sur f ace ar ea i s %. 2f \ n' , 2*pi *r ad*ht )
case 2
r ad = i nput ( ' Ent er t he r adi us of t he ci r cl e: ' ) ;
f pr i nt f ( ' The ar ea i s %. 2f \ n' , pi *r ad*r ad)
case 3
l en = i nput ( ' Ent er t he l engt h: ' ) ;
wi d = i nput ( ' Ent er t he wi dt h: ' ) ;
f pr i nt f ( ' The ar ea i s %. 2f \ n' , l en*wi d)
ot her wi se
di sp( ' Er r or ! Not a val i d choi ce. ' )
end
32)Writeascriptthatpromptstheuserforavalueofavariablex.Then,itusesthe
menufunctiontopresentchoicesbetweensin(x),cos(x),andtan(x).Thescript
willprintwhicheverfunctionofxtheuserchooses.Useanifelsestatementto
accomplishthis.
Ch3Ex32.m
%Pr i nt s ei t her si n, cos, or t an of x
%uses t he menu f unct i on t o choose
x = i nput ( ' Ent er a val ue f or x: ' ) ;
choi ce = menu( ' Choose a f unct i on' , ' si n' , ' cos' , ' t an' ) ;
i f choi ce == 1
f pr i nt f ( ' si n( %. 1f ) i s %. 1f \ n' , x, si n( x) )
el sei f choi ce == 2
f pr i nt f ( ' cos( %. 1f ) i s %. 1f \ n' , x, cos( x) )
el sei f choi ce == 3
f pr i nt f ( ' t an( %. 1f ) i s %. 1f \ n' , x, t an( x) )
end
33)Modifytheabovescripttouseaswitchstatementinstead.
Ch3Ex33.m
%Pr i nt s ei t her si n, cos, or t an of x
%uses t he menu f unct i on t o choose
x = i nput ( ' Ent er a val ue f or x: ' ) ;
choi ce = menu( ' Choose a f unct i on' , ' si n' , ' cos' , ' t an' ) ;
swi t ch choi ce
case 1
f pr i nt f ( ' si n( %. 1f ) i s %. 1f \ n' , x, si n( x) )
case 2
f pr i nt f ( ' cos( %. 1f ) i s %. 1f \ n' , x, cos( x) )
case 3
f pr i nt f ( ' t an( %. 1f ) i s %. 1f \ n' , x, t an( x) )
end
34)Writeafunctionthatwillreceiveonenumberasaninputargument.Itwilluse
themenufunctionthatwilldisplayChooseafunctionandwillhavebuttons
labeledceil,round,andsign.Usingaswitchstatement,thefunctionwillthen
calculateandreturntherequestedfunction(e.g.,ifroundischosen,thefunction
willreturntheroundedvalueoftheinputargument).
choosefn.m
f unct i on out ar g = choosef n( i nar g)
%Chooses whet her t o use cei l , r ound, or si gn
%on t he i nput ar gument
%For mat of cal l : choosef n( i nput ar g)
%Ret ur ns cei l ( i nput ar g) or r ound or si gn
choi ce = menu( ' Choose a f unct i on' , ' cei l ' , ' r ound' , ' si gn' ) ;
swi t ch choi ce
case 1
out ar g = cei l ( i nar g) ;
case 2
out ar g = r ound( i nar g) ;
case 3
out ar g = si gn( i nar g) ;
end
end
35)ModifythefunctioninQuestion34touseanestedifelsestatementinstead.
choosefn2.m
f unct i on out ar g = choosef n2( i nar g)
%Chooses whet her t o use cei l , r ound, or si gn
%on t he i nput ar gument
%For mat of cal l : choosef n( i nput ar g)
%Ret ur ns cei l ( i nput ar g) or r ound or si gn
choi ce = menu( ' Choose a f unct i on' , ' cei l ' , ' r ound' , ' si gn' ) ;
i f choi ce == 1
out ar g = cei l ( i nar g) ;
el sei f choi ce == 2
out ar g = r ound( i nar g) ;
el sei f choi ce == 3
out ar g = si gn( i nar g) ;
end
end
36)Simplifythisstatement:
i f num< 0
num= abs( num) ;
el se
num= num;
end
i f num< 0
num= abs( num) ;
end
%or j ust :
num= abs( num) ;
37)Simplifythisstatement:
i f val >= 4
di sp( ' OK' )
el sei f val < 4
di sp( ' smal l er ' )
end
i f val >= 4
di sp( ' OK' )
el se
di sp( ' smal l er ' )
end