Professional Documents
Culture Documents
Lecture5
Lecture5
Warmupexercise
Writeaforloopthatcalculatesthefirst20Fibonaccinumbers.Placeresultinavector
Fibo,sothatFibo(n)isthenthnumber.Recallthatthesequencesatisfies:
F(1)=1
F(2)=1
forn>2
F(n)=F(n1)+F(n2)
whileStatements
Sometime,youneedtoiteratemanytimesbutdon'treallywanttocreateavector,oryoudon't
knowinadvancehowmanytimeyouneedtoiterate...forthisyoucanuseawhilestatement.
Thesyntaxforawhilestatementis
whileexpression
a
bunch
of
statements
end
Atthebeginningofeachiteration,Matlabevaluatestheexpressionatthetopoftheloop.ifit
istrue,Matlabexecutesthestatementstotheend.Ifitisfalse,Matlabjumpstotheend
andcontinuesafterit.
So,forexample:
>>x=10
>>whilex>0
x=x1
end
>>
willprintoutallthenumbersfrom9to0(includingboth)
Takenoteoftwothings:
Matlabdoesnotchecktheexpressionallthetime.Onlybeforestartinganewiteration
Iftheexpressionatthetopisfalsewhenthefirstiterationshouldstart,itwillnot.
Exercises
http://ocw.mit.edu/ans7870/resources/farjoun/Lecture5.html
1/3
9/7/2015
Lecture5
Findthevalueofthe100thFibonaccinumber,usingawhileloop,andnobigvectors.
Writeyourprimecheckingprogramusingawhileloopinsteadofaforloop.
Writeawhileloopthatmodifiesn.ifnisevenitchangesnton/2,otherwise,it
changesitto3n+1.ifnis1theloopstops.Trythisoutforseveraldifferentstarting
values.Counthowmanystepsyouneedtogetto1.
Definingyourownfunction
WhileMatlabhasavastcollectionoffunctions,sometimesyouwanttoaddsomeofyour
own.Afunctionshouldbethoughtofasablackbox,withaslotinthetop(fortheinput)anda
draweratthebottomfortheoutput.Whenyougivethefunctioninput("callthefunction"),it
calculatestheoutputandputsitinthedrawer("returnsit").Oncethefunctioniswritten,you
donotneedtocareabouthowitworks.
Functionsmustbedefinedintheirownfile,andthenameofthefilemustmatchthenameof
thefunction.So,forexample,todefineafunctioncalledexample_function_1,createafile
namedexample_function_1.m.Thatfilemuststartwiththekeywordfunction,so
functiony=example_function_1(x)
isthefirstlineofthefile.let'sdissectthisfirstline:
function
AsIsaid,thefirstwordmustbe"function".
y=
Thisdeclaresthelocalnameofavariablewhosevaluewill
bereturnedwhentheexecutionofthefunctionisover.
example_function_1
Thenameofthefunction.Thismustmatchthenameofthe
file.
(x)
Thelocalnameofthevariablethatwillcontaintheinput
value.
Sotherestofthefilecouldbe
y=2*x
end
admittedly,averyboringfunction:Ittakestheinputvalue(locallycalledx),doublesit,and
assignsthatresulttoy.Sinceyisdeclaredtobethereturnvalueandthefunctionhas
ended,thereturnvalueissimplytwicetheinput.
wecallthefunctionbygivingitavalue:
>>example_function_1(17)
or
>>example_function_1(rand)
http://ocw.mit.edu/ans7870/resources/farjoun/Lecture5.html
2/3
9/7/2015
Lecture5
Thereturnvaluecanthenbeassignedtoanothervariable:
>>z=example_function_1(18)
>>z
VariableScope
Animportantdifferencebetweenafunctionandascript(thefilesthatdon'thave"function"as
theirfirstwordarecalledscripts)isthatof"variablescope".
Whenexecutingascriptfromthecommandline,thescriptshasaccesstoallthevariablesthat
aredefinedonthecommandline.Forinstance,ifyouhaveascriptcalledscript1.mwhose
contentsare
x+1
y=y/2
andyourunthisscriptfromthecommandlinelikeso:
>>x=2
>>y=6
>>script1
>>y
Youwillseethatthescriptknowsthatx=2andthaty=6.Notonlythis,notethatyischanged
inthescripts,thenewvalueofy,3isalsothevalueofywhencheckonthecommand
line.Thisseemsnatural,perhaps,butthisisnothowfunctionsbehave.Afunctionwiththe
samecontentfunction1.m
functionfunction1
x+1
y=y/2
willfailtorun,sincewithinthefunctiontherearenosuchvariablesxandy.Thevariablesof
thefunction,aredifferentfromthevariablesoutsidethefunction,eveniftheyhave
thesamename.
changeyourprimecheckingprogramsothattheinputisthenumber,andtheoutputis1
ifthenumberisprimeand0ifnot.
changeyournchangingprogram,sothattheinputistheinitialvalueofnandtheoutput
isthenumberofstepsittooktoreach1.
useyourprimecheckingfunctioninanotherprogram(canbeascript)thatfinds(a)the
1000thprimenumberand(b)thefirstprimenumbergreaterthan1000000.
useyournchangingfunctioninanotherprogram(canbeascript)thatfindsthenumber
ofiterationsneededforthefirst100numbers,andplotsthennicely.
http://ocw.mit.edu/ans7870/resources/farjoun/Lecture5.html
3/3