Sei sulla pagina 1di 11

21/03/2017 AMATLABPrimer

AMATLABPrimer
CONTENTS
THEBASICS
CONDITIONALSTATEMENTSANDLOOPING
SCRIPTSANDFUNCTIONS
DEBUGGING
OTHERDATATYPES
ANEXTENDEDEXAMPLE

NextPreviousTop

THEBASICS
MATLABisaprogramminglanguageandacomputingenvironmentthatusesmatricesasoneofitsbasicdatatypes.ItisacommercialproductdevelopedanddistributedbyMathWorks.
Becauseitisahighlevellanguagefornumericalanalysis,numericalcodetobewrittenverycompactly.Forexample,supposeyouhavedefinedtwomatrices(moreonhowtodothat
presently)thatyoucallAandBandyouwanttomultiplythemtogethertoformanewmatrixC.Thisisdonewiththecode
C=A*B
(notethatexpressionsgenerallyterminatewithasemicoloninMATLAB).Inadditiontomultiplication,moststandardmatrixoperationsarecodedinthenaturalwayforanyonetrainedin
basicmatrixalgebra.Thusthefollowingcanbeused
A+B
AB
A'forthetransposeofA
inv(A)fortheinverseofA
det(A)fordeterminantofA
diag(A)foravectorequaltothediagonalelementsofA
Withtheexceptionoftranspositionallofthesemustbeusedwithappropriatesizedmatrices,e.g.,squarematricestoinvanddetandconformablematricesforarithmeticoperations.

Inaddition,standardmathematicaloperatorsandfunctionsaredefinedthatoperateoneachelementofamatrix.Forexample,supposeAisdefinedasthe2x1matrix
[23]
thenA.^2(.^istheexponentiationoperator)yields
[49]
(notA*Awhichisnotdefinedfornonsquarematrices).Functionsthatoperateoneachelementinclude
exp,ln,sqrt,cos,sin,tan,arccos,arcsin,arctan,andabs.
Inadditiontothesestandardmathematicalfunctionsthereareanumberoflessstandardbutusefulfunctionssuchascumulativedistributionfunctionsforthenormal:cdfn(intheSTATS
toolbox).Theconstantpiisalsoavailable.

MATLABhasalargenumberofbuiltinfunctions,farmorethancanbediscussedhere.AsyouexplorethecapabilitiesofMATLABausefultoolisMATLABshelpdocumentation.Try
typinghelpwinatthecommandpromptthiswillopenagraphicalinterfacewindowthatwillletyouexplorethevarioustypeoffunctionsavailable.Youcanalsotypehelporhelpwin
followedbyaspecificcommandorfunctionnameatthecommandprompttogethelponaspecifictopic.BeawarethatMATLABcanonlyfindafunctionifitiseitherabuiltinfunctionoris
inafilethatislocatedinadirectoryspecifiedbytheMATLABpath.Ifyougetafunctionorvariablenotfoundmessage,youshouldchecktheMATLABpath(usingpathtoseeifthe
functionsdirectoryisincluded)orusethecommandaddpathtoaddadirectorytotheMATLABpath.Alsobeawarethatfileswiththesamenamecancauseproblems.IftheMATLABpath

http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 1/11
21/03/2017 AMATLABPrimer

hastwodirectorieswithfilescalledTIPTOP.m,andyoutrytousethefunctionTIPTOP,youmaynotgetthefunctionyouwant.Youcandeterminewhichisbeingusedwiththewhich
command,e.g.,whichtiptop,andthefullpathtothefilewherethefunctioniscontainedwillbedisplayed.

Afewotherbuiltinfunctionsoroperatorsareextremelyuseful,especially
index=start:increment:end
createsarowvectorofevenlyspacedvalues.Forexample,
i=1:1:10
createsthevector[12345678910].Itisimportanttokeeptrackofthedimensionsofmatricesthesizefunctiondoesthis.Forexample,ifAis3x2,
size(A,1)
returnsa3and
size(A,2)
returnsa2.Thesecondargumentofthesizefunctionisthedimension:thefirstdimensionofamatrixistherows,thesecondisthecolumns.Ifthedimensionisleftouta1x2vectoris
returned:
size(A)
returns[32].

Thereareanumberofwaystocreatematrices.Oneisbyenumeration
X=[1521]
whichdefinesXtobethe2x2matrix
15
21
Theindicatestheendofarow(actuallyitisaconcatenationoperatorthatallowyoutostackmatricesmoreonthatbelow).Otherwaystocreatematricesinclude
X=ones(m,n)
and
X=zeros(m,n)
whichcreatemxnmatriceswitheachelementequalto1or0,respectively.MATLABalsohasseveralrandomnumbergeneratorswithasimilarsyntax.
X=rand(m,n)
createsanmxnmatrixofindependentrandomdrawsfromauniformdistribution(actuallytheyarepseudorandom).
X=randn(m,n)
drawsfromthestandardnormaldistribution.

Individualelementsofamatrixthesizeofwhichhasbeendefinedcanbeaccessedusing()forexampleifyouhavedefinedthe3x2matrixB,youcansetelement1,2equaltocos(2.5)with
thestatement
B(1,2)=cos(5.5)
Ifyouthenwhattosetelement2,1tothesamevalueuse
B[2,1]=B[1,2]
Awholecolumnorrowofamatrixcanbereferencedaswellinthefollowingway
B(:,1)
referstocolumn1ofthematrixBand
B(3,:)
referstoitsthirdrow.The:isanoperatorthatselectsalloftheelementsintheroworcolumn.Anequivalentexpressionis
B(3,1:end)
whereendindicatesthecolumninthematrix.

http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 2/11
21/03/2017 AMATLABPrimer

Youcanalsopickandchoosetheelementsyouwant,e.g.,
C=B([13],2)
resultsinanew2x1matrixequalto
B12
B32
Alsotheconstruction
B(1:3,2)
isusedtorefertorows1through3andcolumn2ofthematrixB.Theabilitytoaccesspartsofamatrixisveryusefulbutalsocancauseproblems.Oneofthemostcommonprogramming
errorsisattemptingtoaccesselementsofamatrixthatdontexistthiswillcauseanerrormessage.

Whileonthesubjectonindexingelementsofamatrix,youshouldknowthatMATLABactuallyhastwodifferentwaysofindexing.Oneistousetherowandcolumnindices,asabove,the
othertousethelocationinthevectorizedmatrix.Whenyouvectorizeamatrixyoustackitscolumnsontopofeachother.Soa3x2matrixbecomesa6x1vectorcomposedofastackoftwo
3x1vectors.Element1,2ofthematrixiselement4ofthevectorizedmatrix.Ifyouwanttocreateavectorizedmatrixthecommand
X(:)
willdothetrick.

MATLABhasapowerfulsetofgraphicsroutinesthatenableyoutovisualizeyourdataandmodels.Forstarters,itwillsufficetonotethatroutinesplot,meshandcontour.Forplottingintwo
dimensions,useplot(x,y).Passingastringasathirdargumentgivesyoucontroloverthecoloroftheplotandthetypeoflineorsymbolused.mesh(x,y,z)providesplotsofa3Dsurface,
whereascontour(x,y,z)projectsa3dsurfaceontotwodimensions.Itiseasytoaddtitles,labelsandtexttotheplotsusingtitle,xlabel,ylabelandtext.Subscripts,superscriptsandGreek
letterscanbeobtainedusingTEXcommands(eg.,x_t,x^2and\alpha\mu).TogainmasteryovergraphicstakessometimethedocumentationUsingMATLABGraphicsavailablewith
MATLABisasgoodaplaceasanytolearnmore.

Youmayhavenoticedthatstatementssometimesendwith(semicolon)andtheydont.MATLABisaninteractiveenvironment,meaningitinteractswithyouasitrunsjobs.It
communicatesthingstoyouviayourdisplayterminal.AnytimeMATLABexecutesanassignmentstatement,meaningthatisassignsnewvaluestovariables,itwilldisplaythevariableon
thescreenUNLESStheassignmentstatementendwithasemicolon.Itwillalsotellyouthenameofthevariable,sothecommand
x=2+4
willdisplay
x=
6
onyourscreen,whereasthecommand
x=2+4
displaysnothing.IfyouaskMATLABtomakesomecomputationbutdonotassigntheresulttoavariable,MATLABwillassignittoanimplicitvariablecalledans(shortfor``answer'').Thus
thecommand
2+4
willdisplay
ans=
6

NextPreviousTop

CONDITIONALSTATEMENTSANDLOOPING
AswithanyprogramminglanguageMATLABcanevaluatebooleanexpressionsuchasA>B,A>=B,A<B,A<=BandA~=B(thelastoneisnotequal~isMATLABsnegationoperator).Also
~(A>B),~(A<B),etc.,canbeused.TheseneedtobeusedwithabitofcasewhenAandBarenotscalars,however.A>BcreatesamatrixofzerosandonesequalinsizetoAandB.Ifyouwant
toknowisanyoftheelementsofAarebiggerthananyoftheelementsofBisthesameascheckingwhetheranyoftheelementsofthematrixA>Barenonzero.MATLABprovidesthe
http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 3/11
21/03/2017 AMATLABPrimer

functionsanyandalltoevaluatematricesresultingformbooleanexpressions.AswithmanyMATLABfunctions,anyandalloperateonrowsandreturnarowsvectorwiththesamenumber
ofcolumnsastheoriginalmatrix.Thisistrueforsumandprodfunctionsaswell.Thefollowingareequivalentexpressions
any(A>B)
and
sum(A>B)>0.
Thefollowingarealsoequivalent:
all(A>B)
and
prod(A>B)>0
Alloftheseexpressionarerowvectors:
size(all(A>B))
isequalto
[1max(size(A),size(B))]

Booleanexpressionsaremainlyusedtohandleconditionalexecutionofcodeusingoneofthefollowing:
ifexpression
...
end
ifexpression
...
else
...
end
and
whileexpression
...
end
Thefirsttwoofthesearesingleconditionals,forexample
ifX>0,A=1/XelseA=0,end
Youshouldalsobeawareoftheswitchcommand(typehelpswitch).
Thelastisforlooping.Usuallyyouusewhileforloopingwhenyoudontknowhowmanytimestheloopistobeexecutedanduseaforloopwhenyouknowhowmanytimesitwillbe
executed.Toloopthroughaprocedurentimesforexample,onecouldusethefollowingcode:
fori=1:n,X(I)=3*X(i1)+1end
Acommonuseofwhileforourpurposeswillbetoiterateuntilsomeconvergencecriteriaismet,suchas
P=2.537
X=0.5
DX=0.5
whileDX<1E7
DX=DX/2
ifnormcdf(X)>P,X=XDXelseX=X+DXend
disp(X)
end
(canyoufigureoutwhatthiscodedoes?).Onethinginthiscodefragmentthathasnotyetbeenexplainedisdisp(X).ThiswillwritethematrixXtothescreen.

http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 4/11
21/03/2017 AMATLABPrimer

NextPreviousTop

SCRIPTSANDFUNCTIONS
WhenyouworkinMATLAByouareworkinginaninteractiveenvironmentthatstoresthevariablesyouhavedefinedandallowsyoutomanipulatethemthroughoutasession.Youdohave
theabilitytosavegroupsofcommandsinfilesthatcanbeexecutedmanytimes.ActuallyMATLABhastwokindsofcommandfiles,calledMfiles.ThefirstisascriptMfile.Ifyousavea
bunchofcommandsinascriptfilecalledMYFILE.mandthentypethewordMYFILEattheMATLABcommandline,thecommandsinthatfilewillbeexecutedjustasifyouhadrunthem
eachfromtheMATLABcommandprompt(assumingMATLABcanfindwhereyousavedthefile).AgoodwaytoworkwithMATLABistouseitinteractively,andthenedityousessionand
savetheeditedcommandstoascriptfile.Youcansavethesessioneitherbycuttingandpastingorbyturningonthediaryfeature(usetheonlinehelptoseehowthisworksbytypinghelp
diary).

ThesecondtypeofMfilesisthefunctionfile.OneofthemostimportantaspectsofMATLABistheabilitytowriteyourownfunctions,whichcanthenbeusedandreusedjustlikeintrinsic
MATLABfunctions.Afunctionfileisafilewithanmextension(e.g.,MYFUNC.m)thatbeginswiththewordfunction.
functionZ=DiagReplace(X,v)
%DiagReplaceReplacethediagonalelementsofamatrixXwithavectorv
%SYNTAX:
%Z=DiagReplace(X,v)
n=size(X,1)
Z=X
ind=(1:n:n*n)+(0:n1)
Z(ind)=v
YoucanseehowthisfunctionworksbytypingthefollowingcodeattheMATLABcommandline:
m=3x=randn(m,m)v=rand(m,1)x,v,xv=diagreplace(x,v)
Anyvariablesthataredefinedbythefunctionthatarenotreturnedbythefunctionarelostafterthefunctionhasfinishedexecuting(nandindintheexample).Hereisanotherexample:
functionx=rndint(k,m,n)
%RANDINTReturnsanmxnmatrixofrandomintegersbetween1andk(inclusive).
%SYNTAX:
%x=rndint(k,m,n)
%Canbeusedforsamplingwithreplacement.
x=ceil(k*rand(m,n))

Documentationoffunctions(andscripts)isveryimportant.InMfilesa%denotesthattherestofthelineisacomment.Commentshouldbeusedliberallytohelpyouandotherswhomight
readyourcodeunderstandwhatthecodeisintendingtodo.Thetoplinesofcodeinafunctionfileareespeciallyimportant.Itisherewhereyoushoulddescribewhatthefunctiondoes,what
itssyntaxisandwhateachoftheinputandoutputvariablesare.Thesetoplinebecomeanonlinehelpfeatureforyourfunction.Forexample,typinghelprandintattheMATLABcommand
linewoulddisplaythefourcommentedlinesonyourscreen.

Anoteofcautiononnamingfilesisinorder.Itisveryeasytogetunexpectedresultsifyougivethesamenametodifferentfunctions,orifyougiveanamethatisalreadyusedbyMATLAB.
Priortosavingafunctionthatyouwrite,itisusefultousethewhichcommandtoseeifthenameisalreadyinuse.

MATLABisveryflexibleaboutthenumberofargumentsthatarepassedtoandfromafunction.Thisisespeciallyusefulifafunctionhasasetofpredefineddefaultsvaluesthatusually
providegoodresults.Forexample,supposeyouwriteafunctionthatiteratesuntilaconvergencecriteriaismetoramaximumnumberofiterationshasbeenreached.Onewaytowritesucha
functionistomaketheconvergencecriteriaandthemaximumnumberofiterationsbeoptionalarguments.Thefollowingfunctionattemptstofindthevalueofxsuchthatln(x)=ax,whereais
aparameter.
functionx=SolveIt(a,tol,MaxIters)
ifnargin<3|isempty(MaxIters),MaxIters=100end

http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 5/11
21/03/2017 AMATLABPrimer

ifnargin<2|isempty(tol),tol=sqrt(eps)end
x=a
fori=1:MaxIters
lx=log(x)
fx=x.*lxa
x=xfx./(lx+1)
disp([xfx])
ifabs(fx)<tol,breakend
end
Inthisexample,thecommandnarginmeans"numberofinputarguments"andthecommandisemptycheckstoseeisavariableispassedbutisempty(anemptyvariableiscreatedbysetting
itto[]).Ananalogousfunctionforthenumberofoutputargumentsisnargoutmanytimesitisusefultoputastatementlike
ifnargout<2,returnend
intoyourfunctionsothatthefunctiondoesnothavedocomputationsthatarenotrequested.

Itispossiblethatyouwantnothingormorethanonethingreturnedfromaprocedure.Forexample
function[m,v]=MeanVar(X)
%MeanVarComputesthemeanandvarianceofadatamatrix
%SYNTAX
%[m,v]=MeanVar(X)
n=size(X,1)
m=mean(X)
ifnargout>1
temp=Xm(ones(n,1),:)
v=sum(temp.*temp)/(n1)
end
Tousethisprocedurecallitwith[mu,sig]=MeanVar(X).Noticethatisonlycomputesthevarianceifmorethanoneoutputisdesired.Thus,thestatementmu=MeanVar(X)iscorrectand
returnsthemeanwithoutcomputingthevariance.

Inthefollowingexample,thefunctioncanacceptoneortwoargumentsandcheckshowmanyoutputsarerequested.Thefunctioncomputesthecovarianceoftwoormorevariables.Itcan
handlebothabivariatecasewhenpassedtwodatavectorsandamultivariatecasewhenpassedasingledatamatrix(treatingcolumnsasvariablesandrowsasobservations).Furthermoreit
returnsnotonlythecovariancebut,ifrequested,thecorrelationmatrixaswell.
function[CovMat,CorrMat]=COVARIANCE(X,Y)
%COVARIANCEComputescovariancesandcorrelations
n=size(X,1)
ifnargin==2
X=[XY]%ConcatenateXandY
end
m=mean(X)%Computethemeans
X=Xm(ones(n,1),:)%Subtractthemeans
CovMat=X'*X./n%Computethecovariance
ifnargout==2%Computethecorrelation,ifrequested
s=sqrt(diag(CovMat))
CorrMat=CovMat./(s*s')
end

http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 6/11
21/03/2017 AMATLABPrimer

Thiscodeexecutesindifferentwaysdependingonthenumberofinputandoutputargumentsused.Iftwomatricesarepassedin,theyareconcatenatedbeforethecovarianceiscomputed,
therebyallowingthefrequentlyusedbivariatecasetobehandled.Thefunctionalsocheckswhetherthecallerhasrequestedoneortwooutputsandonlycomputesthecorrelationif2are
requested.Althoughitwouldnotbeamistaketojustgoaheadandcomputethecorrelation,thereisnopointifitisnotgoingtobeused.Unlessadditionaloutputargumentsmustbe
computedanyway,itisgoodpracticetocomputethemonlyasneeded.Someexamplesofcallingthisfunctionare
c=COVARIANCE(randn(10,3))
[c1,c2]=COVARIANCE((1:10)',(2:2:20)')

Gooddocumentationisveryimportantbutitisalsousefultoincludesomeerrorcheckinginyourfunctions.Thismakesitmucheasiertotrackdownthenatureofproblemswhentheyarise.
Forexample,ifsomeargumentsarerequiresand/ortheirvaluesmustmeetsomespecificcriteria(theymustbeinaspecifiedrangeorbeintegers)thesethingsareeasilychecked.Forexample,
considerthefunctionDiagReplacelistedabove.Thisisintendedforasquarematrix(nxn)Xandannvectorv.Bothinputsareneededandtheymustbeconformable.Thefollowingcode
putsinerrorchecks.
functionZ=DiagReplace(X,v)
%DiagReplaceReplacethediagonalelementsofamatrixXwithavectorv
%SYNTAX:
%Z=DiagReplace(X,v)
ifnargin<2,error(2inputsarerequired)end
n=size(X,1)
ifsize(X,2)~=n,error(Xisnotsquare)end
ifprod(size(v))~=n,error(Xandvarenotconformable)end
Z=X
ind=(1:n:n*n)+(0:n1)
Z(ind)=v
ThecommanderrorinafunctionfileprintsoutaspecifiederrormessageandreturnstheusertotheMATLABcommandline.

AnimportantfeatureofMATLABistheabilitytopassafunctiontoanotherfunction.Forexample,supposethatyouwanttofindthevaluethatmaximizesaparticularfunction,sayf(x)=
x*exp(0.5x 2).Itwouldusefulnottohavetowritetheoptimizationcodeeverytimeyouneedtosolveamaximizationproblem.Instead,itwouldbebettertohavesolverthathandles
optimizationproblemsforarbitraryfunctionsandtopassthespecificfunctionofinteresttothesolver.Forexample,supposewesavethefollowingcodeasaMATLABfunctionfilecalled
MYFUNC.m
functionfx=myfunc(x)
fx=x.*exp(0.5*x.^2)
FurthermoresupposewehaveanotherfunctioncallMAXIMIZE.mwhichhasthefollowingcallingsyntax
functionx=MAXIMIZE(f,x0)
Thetwoargumentsarethenameofthefunctiontobemaximizedandastartingvaluewherethefunctionwillbeginitssearch(thisisthewaymanyoptimizationroutineswork).Onecould
thencallMAXIMIZEusing
x=maximize(myfunc,0)
and,iftheMAXIMIZEfunctionknowswhatitsdoing,itwillreturnthevalue1.Noticethatthewordmyfuncisenclosedinsinglequotes.Itisthenameofthefunction,passedasastring
variable,thatispassedin.ThefunctionMAXIMIZEcanevaluateMYFUNCusingthefevalcommand.Forexample,thecode
fx=feval(f,x)
isusedtoevaluatethefunction.Itisimportanttounderstandthatthefirstargumenttofevalisastringvariable(youmayalsowanttofindoutaboutthecommandeval,butthisisonlya
primer,notamanual).

Itisoftenthecasethatfunctionshaveauxiliaryparameters.Forexample,supposewechangedMYFUNCto
functionfx=myfunc(x,mu,sig)
fx=x.*exp(0.5*((xmu)./sig).^2)

http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 7/11
21/03/2017 AMATLABPrimer

NowtherearetwoauxiliaryparametersthatareneededandMAXIMIZEneedstobealteredtohandlethissituation.MAXIMIZEcannotknowhowmanyauxiliaryparametersareneeded,
however,soMATLABprovidesaspecialwaytohandlejustthissituation.Havethecallingsequencebe
functionx=MAXIMIZE(f,x0,varargin)
and,toevaluatethefunction,use
fx=feval(f,x,varargin{:})
Thecommandvarargin(variablenumberofinputarguments)isaspecialwaythatMATLABhasdesignedtohandlevariablenumbersofinputarguments.Althoughitcanbeusedinavariety
ofwaysthesimplestisshownhere,whereitsimplypassesalloftheinputargumentsafterthesecondontofeval.Dontworrytoomuchifthisisconfusingatfirst.Untilyoustartwritingcode
toperformgeneralfunctionslikeMAXIMIZEyouwillprobablynotneedtousethisfeatureinyourowncode,butitishandytohaveanideaofwhatitsforwhenyouaretryingtoreadother
peoplescode.

NextPreviousTop

DEBUGGING
Bugsinyourcodeareinevitable.Learninghowtodebugcodeisveryimportantandwillsaveyoulotsoftimeandaggravation.Debuggingproceedsinthreesteps.Thefirstensuresthatyour
codeissyntacticallycorrect.Whenyouattempttoexecutesomecode,MATLABfirstscansthecodeandreportsanerrorthefirsttimeitfindsasyntaxerror.Theseerrors,knownascomplie
errors,aregenerallyquiteeasytofindandcorrect(onceyouknowwhattherightsyntaxis).Thesecondstepinvolvesfindingerrorsthataregeneratedasthecodeisexecuted,knownasrun
timeerrors.MATLABhasabuiltineditor/debuggeranditisthekeytoefficientdebuggingofruntimeerrors.Ifyourcodefailsduetoruntimeerrors,MATLABreportstheerrorandprovides
atraceofwhatwasbeingdoneatthepointwheretheerroroccurred.Oftenyouwillfindthatanerrorhasoccurredinafunctionthatyoudidntwritebutwascalledbyafunctionthatwas
calledbyafunctionthatwascalledbyafunction(etc.)thatyoudidwrite.Asafefirstassumptionisthattheproblemliesinyourcodeandyouneedtocheckwhatyourcodewasdoingthat
ledtotheeventualerror.

Thefirstthingtodowithruntimeerrorsistomakesurethatyouareusingtherightsyntaxincallingwhateverfunctionyouarecalling.Thismeansmakingsureyouunderstandwhatthat
syntaxis.Mosterrorsofthistypeoccurbecauseyoupassthewrongnumberofarguments,theargumentsyoupassarenotoftheproperdimensionortheargumentsyoupasshave
inappropriatevalues.Ifthesourceoftheproblemisnotobvious,itisoftenusefultousethedebugger.Todothis,clickonFileandtheeitherOpenorNewfromwithinMATLAB.Onceinthe
editor,clickonDebug,thenonStopiferror.Nowrunyourprocedureagain.WhenMATLABencountersanerror,itnowentersadebuggingmodethatallowsyoutoexaminethevaluesofthe
variablesinthevariousfunctionsthatwereexecutingatthetietheerroroccurs.Thesecanbeaccessedbyselectingafunctioninthestackontheeditor'stoolbar.Thenplacingyourcursor
overthenameofavariableinthecodewillallowyoutoseewhatthatvariablecontains.YoucanalsoreturntotheMATLABcommandlineandtypecommands.Theseareexecutedusingthe
variablesinthecurrentlyselectedworkspace(theoneselectedintheStack).Generallyalittleinvestigationwillrevealthesourceoftheproblem(asinallthings,itbecomeseasierwith
practice).

Thereisathirdstepindebugging.Justbecauseyourcoderunswithoutgeneratinganerrormessage,itisnotnecessarilycorrect.Youshouldcheckthecodetomakesureitisdoingwhatyou
expect.Onewaytodothisistotestitoneaproblemwithaknowsolutionorasolutionthatcanbecomputedbyanalternativemethod.Afteryouhaveconvincedyourselfthatitisdoing
whatyouwantitto,checkyoudocumentationandtrytothinkuphowitmightcauseerrorswithotherproblems,putinerrorchecksasappropriateandthencheckitonemoretime.Then
checkitonemoretime.

Afewlastwordsofadviceonwritingcodeanddebugging.
(1)Breakyourproblemdownintosmallchunksanddebugeachchunkseparately.Thisusuallymeanswritelotsofsmallfunctionfiles(anddocumentthem).
(2)Trytomakefunctionsworkregardlessofthesizeoftheparameters.Forexample,ifyouneedtoevaluateapolynomialfunction,writeafunctionthatacceptsavectorofvaluesanda
coefficientvector.Ifyouneedsuchafunctiononceitislikelyyouwillneeditagain.Alsoifyouchangeyourproblembyusingafifthorderpolynomialratherthanafourthorder,youwillnot
needtorewriteyourevaluationfunction.
(3)Trytoavoidhardcodingparametervaluesanddimensionsintoyourcode.Supposeyouhaveaproblemthatinvolvesaninterestrateof7%.Dontputalotof0.07sintoyourcode.Later
onyouwillwanttoseewhathappenswhentheinterestrateis6%andyoushouldbeabletomakethischangeinasinglelinewithanicecommentattachedtoit,e.g.,
rho=0.07%theinterestrate
(4)Avoidloopsifpossible.LoopsareslowinMATLAB.Itisoftenpossibletodothesamethingthataloopdoeswithavectorizedcommand.Learntheavailablecommandsandusethem.

http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 8/11
21/03/2017 AMATLABPrimer

(5)RTFMinternetlingomeaningReadThe(Fwordofchoice)Manual.
(6)Whenyoujustcantfigureitout,checktheMATLABtechnicalsupportsite(MathWorks),theMATLABdiscussiongroup(comp.softsys.matlab)andDejaNewsforpostingaboutyour
problemandifthatturnsupnothing,postaquestiontothediscussiongroup.Dontoverdoit,howeverpeoplewhoabusethesegroupsarequicklyspottedandwillhavetheirquestions
ignored.Alsodontaskthegrouptosolveyourhomeworkproblemsyouwillgetfarmoreoutofattemptingthemyourselfthenyoullgetoutofhavingsomeoneelsetellyoutheanswer.You
arelikelytobefoundoutanywayanditisaformofcheating.

NextPreviousTop

OTHERDATATYPES
Sofarwehaveonlyusedvariablesthatarescalars,vectorormatrices.MATLABalsorecognizesmultidimensionalarrays.Elementbyelementarithmeticworksasusualonthesearrays
(includingadditionandsubtraction,aswellasbooleanarithmetic).MatrixarithmeticisnotclearlydefinedformultidimensionalarraysandMATLABhasnotattemptedtodefineastandard.
Ifyoutrytomultiplytwomultidimensionalarrays,youwillgenerateanerrormessage.Workingwithmultidimensionalarrayscangetabittrickybutisoftenthebestwaytohandlecertain
kindsofproblems.AnalternativetomultidimensionalarraysiswhatMATLABcallsacellarray.Amultidimensionalarraycontainsnumbersforelements.Acellarrayisanarray(possiblya
multidimensionalone)thatotherdatastructuresaselements.Forexample,youcandefinea2x1cellarraythatcontainsa3x1matrixinitfirstcell(i.e.,aselement(1,1))anda4x4matrixin
itssecondcell.Cellarraysaredefinedusingcurlybracketsratherthansquareones,e.g.,
x={[12],[1234]}

OtherdatatypesareavailableinMATLABincludestringvariables,structurevariablesandobjects.Astringvariableisselfexplanatory.Structurevariablesarevariablesthathavenamed
fieldsthatcanbereferenced.Forexample,astructurevariable,X,couldhavethefieldsDATEandPRICE.OnecouldthenrefertothedatacontainedinthesefiledusingX.DATEand
X.PRICE.Ifthestructurevariableisitselfanarray,onecouldrefertofieldsofanelementinthestructureusingX(1).DATEandX(1).PRICE.

Objecttypevariablesarelikestructuresbuthavemethodsattachedtothem.Thefieldsofanobjectcannotbedirectlyaccessedbutmustbeaccessusingthemethodsassociatedwiththe
object.StructuresandobjectsareadvancedtopicsthatarenotneededtogetstartedusingMATLAB.Theyarequiteusefulifyouaretryingtodesignuserfriendlyfunctionsforotherusers.It
isalsousefultounderstandobjectswhenworkingwithMATLAB'sgraphicalcapabilities,although,again,youcangetprettyniceplotswithoutdelvingintohowobjectswork.

NextPreviousTop

ANEXTENDEDEXAMPLE
Thefollowingexampleisabitmoreelaborateandisactuallyusefulcode.Itconstructsestimatesofthemeanandstandarderrorofastatisticusingaresampling(bootstrapping)method.It
thendemonstratestheuseoftheprocedurewithanillustrationfromajournalarticle.Thecodeusesthetechniqueofpassingafunctiontoanotherfunction.Thisallowsthebootstrapping
programtobereusedfordifferentstatisticswithouthavingtoalteranyofitscode.Thiswasdiscussedingeneraltermsinthesectionaboveonfunctions.Recallfromthatdiscussionthatitis
thenameofafunctionfilethatispassedandthenthecommandfevalisusedtoevaluatethefunction.InthiscasethenameofthefunctionispassedtoBOOTasitssecondargument,stat.

HerewehavedefinedafunctionandsavedittoafilenamedBOOT.m

%BOOTComputesbootstrapestimates
%Bootstrappedmeanandstandarderrorofauserspecifiedstatistic.
%SYNTAX
%[mean,stderr]=boot(data,stat,rep)
%Inputs:
%DATAamatrixcontainingthedatausedincomputing
%thestatistic
%STATaprocedurewithasingleinput(adatamatrix)that
%computesthedesiredstatistic(canreturnavector)

http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 9/11
21/03/2017 AMATLABPrimer

%REPthenumberofbootstrapreplicationsperformed
%Outputs:
%MEANthesimulatedmeanvalueofthestatistic
%STDERRthebootstrapstandarderrorofthestatistic
function[mean,stderr]=boot(data,stat,rep)
ndata=size(data,1)
cum=0
cum2=0
i=0
fori=1:rep
ind=randint(ndata,ndata,1)
s=feval(stat,data(ind,:))
cum=cum+s
cum2=cum2+s.^2
end
mean=cum./rep
stderr=sqrt((cum2(cum.^2)/rep)/(rep1))

Nowdefineafunctiontocomputethecorrelationcoefficientfor2variablestoredinthecolumnsofannx2matrixX.SavethisfileasRHO.M.

functionrho=CorrStat(x)
%CorrStatCorrelationcoefficient
n=size(x,1)
m=mean(x)
x=xm(ones(n,1),:)
V=x*x
rho=V(2,1)/sqrt(V(1,1)*V(2,2))

Thefollowingisascriptfilethatcanbeexecutedbytypingitsfilename(withoutextension)attheMATLABcommandline.NoticehowitpassesthenameCorrStattothefunctionBOOT.

%Examplefrom
%Efron,B.andR.Tibshrani.
%"BootstrapMethodsforStandardErrors,ConfidenceIntervals
%andOthermeasuresofStatisicalAccuracy."
%StatisticalScience,1(1986):5477.
%LawSchoolData:bootstrapestimatesofthecorrelation
%betweenLSATandGPAscores.
%Thesamplecorrelationcoefficientis0.776.
%Normaldistributiontheoryyieldsastandarderror
%forthisstatisticof0.115.
%Theauthorsreportedabootstrapestimateof0.127.
lawdata=[
5763.39
6353.30
5582.81
http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 10/11
21/03/2017 AMATLABPrimer

5783.03
6663.44
5803.07
5553.00
6613.43
6513.36
6053.13
6533.12
5752.74
5452.76
5722.88
5942.96]
[m,s]=boot(lawdata,CorrStat,10)
disp(Bootstrapestimateofthestandarderror:)
disp(s)

PreviousTop

Copyright,1998,PaulL.Fackler,NorthCarolinaStateUniversity.
LastModified:December28,1998

http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm#ExtendedExample 11/11

Potrebbero piacerti anche