Sie sind auf Seite 1von 19

Chapter 4: Loop Statements

Exercises

1)Writeaforloopthatwillprintthecolumnofrealnumbersfrom1.5to3.1in
stepsof0.2.

f or i = 1. 5: 0. 2: 3. 1
di sp( i )
end

2)Writeafunctionsumsteps2thatcalculatesandreturnsthesumof1toninsteps
of2,wherenisanargumentpassedtothefunction.Forexample,if11ispassed,it
willreturn1+3+5+7+9+11.Dothisusingaforloop.Callingthefunctionwill
looklikethis:
>> sumsteps2(11)
ans =
36

sumst eps2. m
f unct i on out sum= sumst eps2( n)
%sumf r om1 t o n i n st eps of 2
%For mat of cal l : sumst eps2( n)
%Ret ur ns 1 + 3 + . . . + n

out sum= 0;
f or i = 1: 2: n
out sum= out sum+ i ;
end
end

3)Writeafunctionprodby2thatwillreceiveavalueofapositiveintegernandwill
calculateandreturntheproductoftheoddintegersfrom1ton(orfrom1ton1ifn
iseven).

prodby2.m
f unct i on out = pr odby2( n)
%Cal cul at es and r et ur ns 1*3*5*. . *n
%For mat of cal l : pr odby2( n)
%Ret ur ns pr oduct f r om1 t o n i n st eps of 2

out = 1;
f or i = 1: 2: n
out = out * i ;
end
end

4)PrompttheuserforanintegernandprintIlovethisstuff!ntimes.

Ch4Ex4.m
%Pr ompt s t he user f or an i nt eger n and pr i nt s
%" I l ove t hi s st uf f " n t i mes

n = i nput ( ' Ent er an i nt eger : ' ) ;
f or i = 1: n
di sp( ' I l ove t hi s st uf f ! ' )
end

5)IntheCommandWindow,writeaforloopthatwilliteratethroughtheintegers
from32to255.Foreach,showthecorrespondingcharacterfromthecharacter
encoding.

>> for i = 32:255


disp(char(i))
end

!
"
#
$
%

et c.

6)IntheCommandWindow,writeaforloopthatwillprinttheelementsfroma
vectorvariableinsentenceformat.Forexample,ifthisisthevector:
>> vec = [5.5 11 3.45];
thiswouldbetheresult:

El ement 1 i s 5. 50.
El ement 2 i s 11. 00.
El ement 3 i s 3. 45.

Theforloopshouldworkregardlessofhowmanyelementsareinthevector.

>> vec = [44 11 2 9 6];


>> for i = 1:length(vec)
fprintf('Element %d is %.2f\n',i,vec(i))
end
El ement 1 i s 44. 00
El ement 2 i s 11. 00
El ement 3 i s 2. 00
El ement 4 i s 9. 00
El ement 5 i s 6. 00

7)Writeascriptthatwill:
- generatearandomintegerintherangefrom2to5
- loopthatmanytimesto
o prompttheuserforanumber
o printthesumofthenumbersenteredsofarwithonedecimalplace

Ch4Ex7. m
%Gener at e a r andomi nt eger and l oop t o pr ompt t he
%user f or t hat many number s and pr i nt t he r unni ng sums

r ani nt = r andi ( [ 2, 5] ) ;
r unsum= 0;
f or i = 1: r ani nt
num= i nput ( ' Pl ease ent er a number : ' ) ;
r unsum= r unsum+ num;
f pr i nt f ( ' The sumso f ar i s %. 1f \ n' , r unsum)
end

Therearemanyapplicationsofsignalprocessing.Voltages,currents,andsoundsare
allexamplesofsignalsthatarestudiedinadiverserangeofdisciplinessuchas
biomedicalengineering,acoustics,andtelecommunications.Samplingdiscretedata
pointsfromacontinoussignalisanimportantconcept.

8)Asoundengineerhasrecordedasoundsignalfromamicrophone.Thesound
signalwassampled,meaningthatvaluesatdiscreteintervalswererecorded
(ratherthanacontinuoussoundsignal).Theunitsofeachdatasamplearevolts.
Themicrophonewasnotonatalltimes,however,sothedatasampleswhichare
belowacertainthresholdareconsideredtobedatavalueswhichweresamples
whenthemicrophonewasnoton,andthereforenotvaliddatasamples.Thesound
engineerwouldliketoknowtheaveragevoltageofthesoundsignal.

Writeascriptthatwillasktheuserforthethresholdandthenumberofdata
samples,andthenfortheindividualdatasamples.Theprogramwillthenprintthe
averageandacountoftheVALIDdatasamples,oranerrormessageiftherewereno
validdatasamples.Anexampleofwhattheinputandoutputwouldlooklikeinthe
CommandWindowisshownbelow.

Please enter the threshold below which samples will be


considered to be invalid: 3.0
Please enter the number of data samples to enter: 7

Please enter a data sample: 0.4
Please enter a data sample: 5.5
Please enter a data sample: 5.0
Please enter a data sample: 2.1
Please enter a data sample: 6.2
Please enter a data sample: 0.3
Please enter a data sample: 5.4

The average of the 4 valid data samples is 5.53 volts.

Note:Intheabsenceofvaliddatasamples,theprogramwouldprintanerror
messageinsteadofthelastlineshownabove.

Ch4Ex8.m
%Aver age val i d dat a sampl es f or a sound engi neer

di sp( ' Pl ease ent er t he t hr eshol d bel ow whi ch sampl es wi l l be' )
t hr esh = i nput ( ' consi der ed t o be i nval i d: ' ) ;
numsamp = i nput ( ' Pl ease ent er t he number of dat a sampl es t o be
ent er ed: ' ) ;
mysum= 0;
mycount = 0;
f or i =1: numsamp
dat asamp = i nput ( ' \ nPl ease ent er a dat a sampl e: ' ) ;
i f dat asamp >= t hr esh
mysum= mysum+ dat asamp;
mycount = mycount + 1;
end
end
i f mycount > 0
f pr i nt f ( ' \ nThe aver age of t he %d val i d dat a sampl es i s %. 2f
vol t s. \ n' , . . .
mycount , mysum/ mycount )
el se
f pr i nt f ( ' Ther e wer e no val i d dat a sampl es. \ n' )
end

9)Writeascriptthatwillloaddatafromafileintoamatrix.Createthedatafile
first,andmakesurethatthereisthesamenumberofvaluesoneverylineinthefile
sothatitcanbeloadedintoamatrix.Usingaforloop,itwillthencreateasmany
FigureWindowsastherearerowsinthematrix,andwillplotthenumbersfrom
eachrowinaseparateFigureWindow.

xfile.dat
4 9 22
30 18 4

Ch4Ex9.m
%l oad dat a f r oma f i l e and pl ot dat a
%f r omeach l i ne i n a separ at e Fi gur e Wi ndow

l oad xf i l e. dat
[ r c] = si ze( xf i l e) ;
f or i = 1: r
f i gur e( i )
pl ot ( xf i l e( i , : ) , ' k*' )
end

10)AmachinecutsNpiecesofapipe.Aftereachcut,eachpieceofpipeisweighed
anditslengthismeasured;these2valuesarethenstoredinafilecalledpipe.dat
(firsttheweightandthenthelengthoneachlineofthefile).Ignoringunits,the
weightissupposedtobebetween2.1and2.3,inclusive,andthelengthissupposed
tobebetween10.3and10.4,inclusive.Thefollowingisjustthebeginningofwhat
willbealongscripttoworkwiththesedata.Fornow,thescriptwilljustcounthow
manyrejectsthereare.Arejectisanypieceofpipethathasaninvalidweight
and/orlength.ForasimpleexampleifNis3(meaningthreelinesinthefile)and
thefilestores:

2. 14 10. 30
2. 32 10. 36
2. 20 10. 35

thereisonlyonereject,thesecondone,asitweighstoomuch.Thescriptwould
print:
Therewere1rejects.

Ch4Ex10.m
%Count s pi pe r ej ect s. I gnor i ng uni t s, each pi pe shoul d be
%bet ween 2. 1 and 2. 3 i n wei ght and bet ween 10. 3 and 10. 4
%i n l engt h

%r ead t he pi pe dat a and separ at e i nt o vect or s
l oad pi pe. dat
wei ght s = pi pe( : , 1) ;
l engt hs = pi pe( : , 2) ;
N = l engt h( wei ght s) ;

%t he pr ogr ammi ng met hod of count i ng
count = 0;

f or i =1: N
i f wei ght s( i ) < 2. 1 | | wei ght s( i ) > 2. 3 | | . . .
l engt hs( i ) < 10. 3 | | l engt hs( i ) > 10. 4
count = count + 1;
end
end

f pr i nt f ( ' Ther e wer e %d r ej ect s. \ n' , count )

11)Improvetheoutputfromthepreviousproblem.Ifthereisonly1reject,it
shouldprintTherewas1reject.;otherwisefornrejectsitshouldprintThere
werenrejects.

Ch4Ex11.m
%Count s pi pe r ej ect s. I gnor i ng uni t s, each pi pe shoul d be
%bet ween 2. 1 and 2. 3 i n wei ght and bet ween 10. 3 and 10. 4
%i n l engt h

%r ead t he pi pe dat a and separ at e i nt o vect or s
l oad pi pe. dat
wei ght s = pi pe( : , 1) ;
l engt hs = pi pe( : , 2) ;
N = l engt h( wei ght s) ;

%t he pr ogr ammi ng met hod of count i ng
count = 0;

f or i =1: N
i f wei ght s( i ) < 2. 1 | | wei ght s( i ) > 2. 3 | | . . .
l engt hs( i ) < 10. 3 | | l engt hs( i ) > 10. 4
count = count + 1;
end
end

i f count == 1
f pr i nt f ( ' Ther e was 1 r ej ect . \ n' )
el se
f pr i nt f ( ' Ther e wer e %d r ej ect s. \ n' , count )
end

12)Whenwoulditmatterifaforloopcontainedf or i = 1: 4vs.
f or i = [ 3 5 2 6] ,andwhenwoulditnotmatter?

Itwouldmatterifthevalueoftheloopvariablewasbeingusedintheactionofthe
loop.Itwouldnotmatteriftheloopvariablewasjustbeingusedtocounthow
manytimestoexecutetheactionoftheloop.

13)Createavectorof5randomintegers,eachintherangefrom10to10.Perform
eachofthefollowingusingloops(withifstatementsifnecessary):

>> vec = r andi ( [ - 10, 10] , 1, 5)

- subtract3fromeachelement

f or i = 1: l engt h( vec)
vec( i ) - 1
end

- counthowmanyarepositive

mysum= 0;
f or i =1: l engt h( vec)
i f vec( i ) > 0
mysum= mysum+ 1;
end
end
mysum

- gettheabsolutevalueofeachelement

f or i = 1: l engt h( vec)
abs( vec( i ) )
end

- findthemaximum

mymax = vec( 1) ;
f or i = 1: l engt h( vec)
i f vec( i ) > mymax
mymax = vec( i ) ;
end
end
mymax

14)Writeafunctionthatwillreceiveamatrixasaninputargument,andwill
calculateandreturntheoverallaverageofallnumbersinthematrix.Useloops,not
builtinfunctions,tocalculatetheaverage.

matave.m
f unct i on out ave = mat ave( mat )
%Cal cul at es t he over al l aver age of number s i n a mat r i x
%usi ng t he pr ogr ammi ng met hods
%For mat of cal l : mat ave( mat r i x)
%Ret ur ns t he aver age of al l el ement s

mysum= 0;
[ r c] = si ze( mat ) ;
f or i = 1: r
f or j = 1: c
mysum= mysum+ mat ( i , j ) ;
end
end
out ave = mysum/ ( r *c) ;
end

15)Wehaveseenthatbydefault,whenusingbuiltinfunctionssuchassumand
prodonmatrices,MATLABwillperformthefunctiononeachcolumn.Adimension
canalsobespecifiedwhencallingthesefunctions.MATLABreferstothecolumnsas
dimension1andtherowsasdimension2,suchasthefollowing:
>> sum( mat , 1)
>> sum( mat , 2)
Createamatrixandfindtheproductofeachrowandcolumnusingprod.

>> mat = r andi ( [ 1, 30] , 2, 3)


mat =
11 24 16
5 10 5

>> pr od( mat )
ans =
55 240 80

>> pr od( mat , 2)
ans =
4224
250

16)Createa3x5matrix.Performeachofthefollowingusingloops(withif
statementsifnecessary):
- Findthemaximumvalueineachcolumn.
- Findthemaximumvalueineachrow.
- Findthemaximumvalueintheentirematrix.

Ch4Ex16.m
%Cr eat e a mat r i x, and use t he pr ogr ammi ng met hods t o f i nd
% t he maxi mumi n each r ow, and each col umn, and over al l

mat = r andi ( [ 1, 30] , 3, 5)
[ r c] = si ze( mat ) ;

%Maxi mumover al l
mymax = mat ( 1, 1) ;
f or i = 1: r
f or j = 1: c
i f mat ( i , j ) > mymax
mymax = mat ( i , j ) ;
end
end
end
f pr i nt f ( ' The over al l max i s %. 1f \ n\ n' , mymax)

%Maxi mumf or each r ow
f or i = 1: r
mymax = mat ( i , 1) ;
f or j = 1: c
i f mat ( i , j ) > mymax
mymax = mat ( i , j ) ;
end
end
f pr i nt f ( ' The max of r ow %d i s %. 1f \ n' , i , mymax)
end
f pr i nt f ( ' \ n' )

%Maxi mumf or each col umn
f or j = 1: c
mymax = mat ( 1, j ) ;
f or i = 1: r
i f mat ( i , j ) > mymax
mymax = mat ( i , j ) ;
end
end
f pr i nt f ( ' The max of col %d i s %. 1f \ n' , j , mymax)
end

17)Withamatrix,whenwould:
- yourouterloopbeovertherows
- yourouterloopbeoverthecolumns
- itnotmatterwhichistheouterandwhichistheinnerloop?

Theouterloopmustbeovertherowsifyouwanttoperformanactionforevery
row;itmustbeoverthecolumnsifyouwanttoperformanactionforeverycolumn.
Itdoesnotmatterifyousimplyneedtorefertoeveryelementinthematrix.

18)Assumethatyouhaveamatrixofintegersmat.Fillintherestofthefprintf
statementsothatthiswouldprinttheproductofeveryrowinthematrix,inthe
format:
The pr oduct of r ow 1 i s 162
The pr oduct of r ow 2 i s 320
et c.
Note:thevalueofcolisnotneeded.

[ r ow col ] = si ze( mat ) ;


f or i = 1: r ow
f pr i nt f ( ' The pr oduct of r ow %d i s %d\ n' , )
end

f pr i nt f ( ' The pr oduct of r ow %d i s %d\ n' , i , pr od( mat ( i , : ) ) )

19)Writeascriptbeautyofmaththatproducesthefollowingoutput.Thescript
shoulditeratefrom1to9toproducetheexpressionsontheleft,performthe
specifiedoperationtogettheresultsshownontheright,andprintexactlyinthe
formatshownhere.

>> beautyofmath
1 x 8 + 1 = 9
12 x 8 + 2 = 98
123 x 8 + 3 = 987
1234 x 8 + 4 = 9876
12345 x 8 + 5 = 98765
123456 x 8 + 6 = 987654
1234567 x 8 + 7 = 9876543
12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

beautyofmath.m
%Shows t he beaut y of mat h!

l ef t num= 0;
f or i = 1: 9
l ef t num= l ef t num* 10 + i ;
r esul t = l ef t num* 8 + i ;
f pr i nt f ( ' %d x 8 + %d = %d\ n' , l ef t num, i , r esul t )
end

20)Writeascriptthatwillprintthefollowingmultiplicationtable:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25

Ch4Ex20.m
%Pr i nt s a mul t i pl i cat i on t abl e

r ows = 5;

f or i = 1: r ows
f or j = 1: i
f pr i nt f ( ' %d ' , i *j )
end
f pr i nt f ( ' \ n' )
end

21)TheWindChillFactor(WCF)measureshowcolditfeelswithagivenair
temperatureT(indegreesFahrenheit)andwindspeedV(inmilesperhour).One
formulaforWCFis
WCF=35.7+0.6T35.7(V
0.16
)+0.43T(V
0.16
)
Writeafunctiontoreceivethetemperatureandwindspeedasinputarguments,and
returntheWCF.Usingloops,printatableshowingwindchillfactorsfor
temperaturesrangingfrom20to55instepsof5,andwindspeedsrangingfrom0
to55instepsof5.Callthefunctiontocalculateeachwindchillfactor.

Ch4Ex21.m
%Pr i nt t abl e of wi nd chi l l f act or s

%Pr i nt col umn header s
f pr i nt f ( ' %45s\ n ' , ' Wi nd Speeds' )
f or v = 0: 5: 55
f pr i nt f ( ' %7d' , v)
end
f pr i nt f ( ' \ nTemp\ n' )

f or t = - 20: 5: 55
f pr i nt f ( ' %3d' , t )
f or v = 0: 5: 55
f pr i nt f ( ' %7. 1f ' , wcf ( t , v) )
end
f pr i nt f ( ' \ n' )
end

wcf.m
f unct i on out wc = wcf ( t , v)
%Cal cul at es t he wi nd chi l l f act or
%For mat of cal l : wcf ( t emper at ur e, wi nd speed)
%Ret ur ns 35. 74 + 0. 6215T ? 35. 75( V^0. 16) + 0. 4275T( V^0. 16)

out wc = 35. 74 + 0. 6215 . * t - 35. 75 . * ( v. ^0. 16) + . . .
0. 4275 . * t . * ( v. ^0. 16) ;
end

22)InsteadofprintingtheWCFsinthepreviousproblem,createamatrixofWCFs
andwritethemtoafile.

Ch4Ex22.m
%Pr i nt t abl e of wi nd chi l l f act or s f or t emper at ur es
%r angi ng f r om- 4 t o 11F and wi nd speeds f r om0 t o 11mph

f or t = - 4: 11
f or v = 0: 11
wcf mat ( t +5, v+1) = wcf ( 5*t , 5*v) ;
end
end

save wcf s. dat wcf mat - asci i

23)Theinverseofthemathematicalconstantecanbeapproximatedasfollows:
1 1
1
| |
~
|
\ .
n
e n

Writeascriptthatwillloopthroughvaluesofnuntilthedifferencebetweenthe
approximationandtheactualvalueislessthan0.0001.Thescriptshouldthenprint
outthebuiltinvalueofe
1
andtheapproximationto4decimalplaces,andalsoprint
thevalueofnrequiredforsuchaccuracy.

Ch4Ex23.m
%Appr oxi mat es 1/ e as ( 1- 1/ n) ^n, and det er mi nes
%t he val ue of n r equi r ed f or accur acy t o 4 dec. pl aces

act ual = 1 / exp( 1) ;
di f f = 1;
n = 0;

whi l e di f f >= 0. 0001
n = n + 1;
appr ox = ( 1 - 1/ n) ^n;
di f f = act ual - appr ox;
end

f pr i nt f ( ' The bui l t - i n val ue of 1/ e i s %. 4f \ n' , act ual )
f pr i nt f ( ' The appr oxi mat i on i s %. 4f \ n' , appr ox)
f pr i nt f ( ' The val ue of n i s %d\ n' , n)

24)Giventhefollowingloop:
whi l e x < 10
act i on
end
- Forwhatvaluesofthevariablexwouldtheactionoftheloopbeskippedentirely?

Theactionwouldbeskippedentirelyifxisgreaterthanorequalto10tobeginwith.

- Ifthevariablexisinitializedtohavethevalueof5beforetheloop,whatwould
theactionhavetoincludeinorderforthistonotbeaninfiniteloop?

Theactionwouldhavetoincrementthevalueofx,sothateventuallyitbecomes
greaterthanorequalto10.

25)Writeascriptthatwillprompttheuserfortheradiusrandheightofacone,
errorchecktheusersinputfortheradiusandtheheight,andthencalculateand
printthevolumeofthecone(volume=/3r
2
h).

Ch4Ex25.m
%Pr ompt t he user f or t he r adi us & hei ght of a cone
%and pr i nt t he vol ume

%Er r or - check t he user ' s i nput s
r ad = i nput ( ' Ent er t he r adi us of t he cone: ' ) ;
whi l e ( r ad <=0)
f pr i nt f ( ' Er r or ! Pl ease ent er a val i d r adi us. \ n' )
r ad = i nput ( ' Ent er t he r adi us of t he cone: ' ) ;
end
ht = i nput ( ' Ent er t he hei ght of t he cone: ' ) ;
whi l e ( ht <=0)
f pr i nt f ( ' Er r or ! Pl ease ent er a val i d hei ght . \ n' )
ht = i nput ( ' Ent er t he hei ght of t he cone: ' ) ;
end

f pr i nt f ( ' The vol i s %. 2f \ n' , ( pi / 3) *r ad*r ad*ht ) ;

26)Writeascript(forexample,calledfindmine)thatwillprompttheuserfor
minimumandmaximumintegers,andthenanotherintegerwhichistheusers
choiceintherangefromtheminimumtothemaximum.Thescriptwillthen
generaterandomintegersintherangefromtheminimumtothemaximum,untila
matchfortheuserschoiceisgenerated.Thescriptwillprinthowmanyrandom
integershadtobegenerateduntilamatchfortheuserschoicewasfound.For
example,runningthisscriptmightresultinthisoutput:

>> findmine
Pl ease ent er your mi ni mumval ue: - 2
Pl ease ent er your maxi mumval ue: 3
Now ent er your choi ce i n t hi s r ange: 0
I t t ook 3 t r i es t o gener at e your number

Ch4Ex26.m
%Pr ompt t he user f or a r ange of i nt eger s and t hen an
%i nt eger i n t hi s r ange. Gener at e r andomi nt eger unt i l
%user ' s i s gener at ed, count i ng how many t r i es i t t ook.

mymi n = i nput ( ' Pl ease ent er your mi ni mumval ue: ' ) ;
mymax = i nput ( ' Pl ease ent er your maxi mumval ue: ' ) ;
mychc = i nput ( ' Now ent er your choi ce i n t hi s r ange: ' ) ;
count er = 1;

myr an = r andi ( [ mymi n, mymax] ) ;
whi l e ( myr an ~= mychc)
myr an = r andi ( [ mymi n, mymax] ) ;
count er = count er + 1;
end
f pr i nt f ( ' I t t ook %d t r i es t o gener at e your number \ n' , count er )

27)WriteascriptthatwillprompttheuserforNintegers,andthenwritethe
positivenumbers(>=0)toanASCIIfilecalledpos.datandthenegativenumbersto
anASCIIfilecalledneg.dat.ErrorchecktomakesurethattheuserentersN
integers.

Ch4Ex27.m
%Pr ompt t he user f or N i nt eger s, wr i t i ng t he posi t i ve
%i nt eger s t o one f i l e and t he negat i ve i nt eger s t o anot her

%i ni t i al i ze vect or s t o st or e pos and neg i nt eger s
posi nt s = [ ] ;
negi nt s = [ ] ;
%l oop n t i mes
n=10;
f or i =1: n
i nput num= i nput ( ' Ent er an i nt eger : ' ) ;
num2 = i nt 32( i nput num) ;
%er r or check t o make sur e i nt eger s ar e ent er ed
whi l e num2 ~= i nput num
i nput num= i nput ( ' I nval i d! Ent er an i nt eger : ' ) ;
num2 = i nt 32( i nput num) ;
end
%add t o appr opr i at e vect or
i f i nput num< 0
negi nt s = [ negi nt s i nput num] ;
el se
posi nt s = [ posi nt s i nput num] ;
end
end

%wr i t e vect or s t o f i l es
save pos. dat posi nt s - asci i
save neg. dat negi nt s - asci i


28) In thermodynamics, the Carnot efficiency is the maximum possible efficiency of a
heat engine operating between two reservoirs at different temperatures. The Carnot
efficiency is given as
1 q =
C
H
T
T

where
C
T and
H
T are the absolute temperatures at the cold and hot reservoirs,
respectively. Write a script that will prompt the user for the two reservoir temperatures in
Kelvin and print the corresponding Carnot efficiency to 3 decimal places. The script
should error-check the users input since absolute temperature cannot be less than or
equal to zero. The script should also swap the temperature values if
H
T is less than
C
T .

Ch4Ex28.m
%Cal cul at es t he Car not ef f i ci ency, gi ven t he t emper at ur es
%of col d and hot r eser voi r s, er r or - checki ng bot h

Tc = i nput ( ' Ent er t he col d r eser voi r t emper at ur e: ' ) ;

whi l e Tc <= 0
Tc = i nput ( ' I nval i d! Ent er t he col d r eser voi r t emper at ur e: ' ) ;
end

Th = i nput ( ' Ent er t he hot r eser voi r t emper at ur e: ' ) ;

whi l e Th <= 0
Th = i nput ( ' I nval i d! Ent er t he hot r eser voi r t emper at ur e: ' ) ;
end

i f Th < Tc
t emp = Th;
Th = Tc;
Tc = t emp;
end

car not Ef f = 1 - ( Tc / Th) ;
f pr i nt f ( ' The Car not ef f i ci ency i s %. 3f \ n' , car not Ef f )

29)Writeascriptthatwillcontinuepromptingtheuserforpositivenumbers,and
storingtheminavectorvariable,untiltheusertypesinanegativenumber.

Ch4Ex29.m
%Pr ompt t he user f or posi t i ve number s and st or e t hem
% i n a vect or unt i l t he user ent er s a negat i ve number

user val s = [ ] ;
newval = i nput ( ' Ent er a posi t i ve number : ' ) ;
whi l e ( newval >= 0)
user val s = [ user val s newval ] ;
newval = i nput ( ' Ent er a posi t i ve number : ' ) ;
end

%di spl ay vect or
user val s

30)Writeascriptecholettersthatwillprompttheuserforlettersofthealphabet
andechoprintthemuntiltheuserentersacharacterthatisnotaletterofthe
alphabet.Atthatpoint,thescriptwillprintthenonletter,andacountofhowmany
letterswereentered.Hereareexamplesofrunningthisscript:

>> echoletters
Ent er a l et t er : T
Thanks, you ent er ed a T
Ent er a l et t er : a
Thanks, you ent er ed a a
Ent er a l et t er : 8
8 i s not a l et t er
You ent er ed 2 l et t er s

>> echoletters
Ent er a l et t er : !
! i s not a l et t er
You ent er ed 0 l et t er s

Theformatmustbeexactlyasshownabove.

echoletters.m
%Echo pr i nt l et t er s unt i l t he user ent er s a char act er
%t hat i s not a l et t er of t he al phabet

count = 0;
i nchar = i nput ( ' Ent er a l et t er : ' , ' s' ) ;

%OR: whi l e i sl et t er ( i nchar )
whi l e ( i nchar >=' a' && i nchar <=' z' ) | | . . .
( i nchar >=' A' && i nchar <=' Z' )
f pr i nt f ( ' Thanks, you ent er ed a %c\ n' , i nchar )
count = count + 1;
i nchar = i nput ( ' Ent er a l et t er : ' , ' s' ) ;
end
f pr i nt f ( ' %c i s not a l et t er \ n' , i nchar )
f pr i nt f ( ' You ent er ed %d l et t er s\ n' , count )

31)Writeascriptthatwillusethemenufunctiontopresenttheuserwithchoices
forfunctionsfix,floor,andceil.Errorcheckbyloopingtodisplaythemenu
untiltheuserpushesoneofthebuttons(anerrorcouldoccuriftheuserclickson
theXonthemenuboxratherthanpushingoneofthebuttons).Then,generatea
randomnumberandprinttheresultoftheusersfunctionchoiceofthatnumber
(e.g.fix(5)).

Ch4Ex31.m
%Make t he user choose a f unct i on ' f i x' , ' f l oor ' or ' cei l '
%and pr i nt t hat f unct i on of a r andomnumber

choi ce = menu( ' Choose a f unct i on' , ' f i x' , ' f l oor ' , ' cei l ' ) ;
whi l e ( choi ce < 1 | | choi ce > 3)
f pr i nt f ( ' Er r or ; pl ease choose a f unct i on! \ n' )
choi ce = menu( ' Choose a f unct i on' , ' f i x' , ' f l oor ' , ' cei l ' ) ;
end

x = r and*10;
swi t ch choi ce
case 1
f pr i nt f ( ' si n( %. 1f ) i s %. 1f \ n' , x, f i x( x) )
case 2
f pr i nt f ( ' cos( %. 1f ) i s %. 1f \ n' , x, f l oor ( x) )
case 3
f pr i nt f ( ' t an( %. 1f ) i s %. 1f \ n' , x, cei l ( x) )
end

32)WriteascriptcalledprtempsthatwillprompttheuserforamaximumCelsius
valueintherangefrom16to20;errorchecktomakesureitsinthatrange.Then,
printatableshowingdegreesFahrenheitanddegreesCelsiusuntilthismaximumis
reached.Thefirstvaluethatexceedsthemaximumshouldnotbeprinted.Thetable
shouldstartat0degreesFahrenheit,andincrementby5degreesFahrenheituntil
themax(inCelsius)isreached.Bothtemperaturesshouldbeprintedwithafield
widthof6andonedecimalplace.TheformulaisC=5/9(F32).Forexample,the
executionofthescriptmightlooklikethis(theformatshouldbeexactlylikethis):

>> prtemps
When pr ompt ed, ent er a t emp i n degr ees C i n r ange - 16
t o 20.
Ent er a maxi mumt emp: 30
Er r or ! Ent er a maxi mumt emp: 9

F C
0. 0 - 17. 8
5. 0 - 15. 0
.
.
.
40. 0 4. 4
45. 0 7. 2

Ch4Ex32. m
%Pr ompt f or a maxi mumC t emper at ur e and pr i nt a t abl e
%showi ng degr ees C and degr ees F

f pr i nt f ( ' When pr ompt ed, ent er a t emp i n degr ees C i n' )
f pr i nt f ( ' r ange - 16\ n t o 20. \ n' )
maxt emp = i nput ( ' Ent er a maxi mumt emp: ' ) ;

%Er r or - check
whi l e maxt emp < - 16 | | maxt emp > 20
maxt emp = i nput ( ' Er r or ! Ent er a maxi mumt emp: ' ) ;
end

%Pr i nt t abl e i ncl ude header s
f pr i nt f ( ' F C\ n' ) ;

f = 0;
c = 5/ 9*( f - 32) ;

whi l e ( c <= maxt emp)
f pr i nt f ( ' %6. 1f %6. 1f \ n' , f , c)
f = f + 5;
c = 5/ 9*( f - 32) ;
end

33)Createanxvectorthathasintegers1through10,andsetayvectorequaltox.
Plotthisstraightline.Now,addnoisetothedatapointsbycreatinganewy2vector
thatstoresthevaluesofyplusorminus0.25.Plotthestraightlineandalsothese
noisypoints.

Ch4Ex33.m
%Cr eat es a st r ai ght l i ne and al so a " noi sy" l i ne
%by addi ng or subt r act i ng 0. 25 r andoml y f r omeach poi nt

x = 1: 10;
y = x;
y2 = y;
pl usMi nus = [ - 1 1] ;
f or i = 1: l engt h( y2)
r an = r andi ( [ 1: 2] ) ;
y2( i ) = y2( i ) + pl usMi nus( r an) *0. 25;
end
pl ot ( x, y, x, y2, ' k*' )

34)Ablizzardisamassivesnowstorm.Definitionsvary,butforourpurposeswe
willassumethatablizzardischaracterizedbybothwindsof30mphorhigherand
blowingsnowthatleadstovisibilityof0.5milesorless,sustainedforatleastfour
hours.Datafromastormonedayhasbeenstoredinafilestormtrack.dat.Thereare
24linesinthefile,oneforeachhouroftheday.Eachlineinthefilehasthewind
speedandvisibilityatalocation.Createasampledatafile.Readthisdatafromthe
fileanddeterminewhetherblizzardconditionsweremetduringthisdayornot.

Ch4Ex34.m
%Reads wi nd and vi si bi l i t y dat a hour l y f r oma f i l e and
%det er mi nes whet her or not bl i zzar d condi t i ons wer e met

l oad st or mt r ack. dat

wi nds = st or mt r ack( : , 1) ;
vi si bs = st or mt r ack( : , 2) ;

l en = l engt h( wi nds) ;
count = 0;
i = 0;
%Loop unt i l bl i zzar d condi t i on f ound or al l dat a
%has been r ead

whi l e count < 4 && i < l en
i = i + 1;
i f wi nds( i ) >= 30 && vi si bs( i ) <= . 5
count = count + 1;
el se
count = 0;
end
end
i f count == 4
f pr i nt f ( ' Bl i zzar d condi t i ons met \ n' )
el se
f pr i nt f ( ' No bl i zzar d t hi s t i me! \ n' )
end

Das könnte Ihnen auch gefallen