Post on 28-May-2020
MatlabCiroDonalek
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
donalek@astro.caltech.edu
Summary• Introduc=ontoMatlab• ProgramminginMatlab– datatypes,variables– loopsvsBuilt‐InFunc=ons
• MatrixandArrayOpera=ons– SubmatricesandColumnNota=on
• M‐Files– script,func=ons
• Visualiza=on• Performanceevalua=onandimproving• AdvancedUse– Compiler,Databaseconnec=on,HowtobuildaGUI...
• ThirdPartytoolboxesAy/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
WhatisMatlab?• MATLABisaninterac=ve,matrix‐basedsystemforscien=ficand
technicalcompu=ng.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
• Itismatrixoriented,thatmeansthatallthematrixopera=onsarehighlyop=mized.
• Itintegratescomputa=on,visualiza=onandprogramminginaneasy‐to‐useenvironment.
TypicalUsesMatlabisusedinmanyfieldsfor:
• MathandComputa=on• AlgorithmDevelopment• DataAcquisi=on• Modeling,Simula=on,andPrototyping• DataAnalysis,Explora=on,andVisualiza=on• Scien=ficandEngineeringGraphics• Applica=onDevelopment,includingGraphicalUserInterfacebuilding
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
Ge[ngMatlab
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
Proprietaryso\ware:distributedbyMathWorks:hAp://www.mathworks.comLatestversion:2009a(releasedMarch6th,2009)
Mul=plaaorm:availableforLinux,Mac,Solaris,Windows.
Supportfor64bitsarchitectures.
*Caltechpersonnelcandownloaditforfreeat:
hAp://so\ware.caltech.edu/
MatlabFamilyProducts• Availablemanytoolboxesforspecificapplica=ons.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
ProgramminginMatlab• TheLanguage
– TheMATLABlanguageisahigh‐levelmatrixorientedlanguagewith:• controlflowstatements(loops,condi=onals)• func=ons,datastructures,input/output,andobject‐orientedprogrammingfeatures
• ithashigh‐levelfunc=onsfortwo‐dimensionalandthree‐dimensionaldatavisualiza=on,imageprocessing,anima=on...
• Mathema=calFunc=onLibrary– Thislibraryisavastcollec=onofcomputa=onalalgorithmsrangingfromelementaryfunc=ons,likesum,sine,cosine,andcomplexarithme=c,tomoresophis=catedfunc=onslikematrixinverse,matrixeigenvalues,andfastFouriertransforms.
• Itcanbeusedforbothsmallandlargeapplica=ons.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
Variables• MATLABdoesnotrequireanytypedeclara=onsordimensionstatements.– newvariablename:automa=callycreatesthevariableandallocatestheappropriateamountofstorage
>>num=3;%createsadouble"num"bydefault– ifthevariablealreadyexists:MATLABchangesitscontents(andallocatesnewstorageifneeded)
>>num=[13];%numbecomesanarray
• Variablename(casesensi=ve)– anylengthbutusesonlythefirstN(namelengthmax)– leAer,followedbyanynumberofleAers,digits,orunderscores
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
SpecialVariables• ans(answer)– whenyoudonotspecifyanoutputvariable,MATLABusesthevariableanstostoretheresultsofacalcula=on
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
>>2+3>>ans=5
• inf(infinite)• NaN• returnstheIEEEarithme=crepresenta=onforNot‐a‐Number
• markerformissingobserva=on• pi,eps,realmin,realmax,etc.
NumericalandLogicalTypes• Numerical
– integer,floa=ngpoint,complex(x=2+3i;)– short,long– allnumbersareinternallystoredaslong– format:changethewayhowthenumbersaredisplayed
• Logical(boolean)– true:1,false:0
• Char– integervalueconvertedtoitsUnicodeequivalent– astringisavectorofcharacters– theactualcharactersdisplayeddependonthecharactersetencoding
foragivenfont
AllMATLABdatatypesareimplementedasobject‐orientedclasses.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
Everythingisa...Matrix
• IntheMATLABamatrixisarectangulararrayofnumbers.– scalarscanbeseenas1‐by‐1matrices;– array(vectors)arematriceswithjustoneroworonecolumn.
• MATLABallowsyoutoworkwithen=rematricesquicklyandeasily.
• Itisusuallybesttothinkofeverythingasamatrix.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
EnteringMatricesMatricescanbeintroducedinseveraldifferentways:
• Enteredbyanexplicitlistofelements>>A=[123;456;789]
• Generatedbybuilt‐instatementsandfunc=ons>>A=rand(3)
• CreatedinM‐filesusingbuilt‐infunc=ons
• Loadedfromexternaldatafiles
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
EnteringMatrices
Basicconven=ons:
• Separatetheelementsofarowwithblanksorcommas.
• Useasemicolon;toindicatetheendofeachrow.
• Surroundtheen=relistofelementswithsquarebrackets[].
>>A=[1,2,3;4,5,6]
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
MatrixandArrayOpera=ons• Matrixopera=onsapplyalsotoscalars(1‐by‐1matrices).
• Ifthesizesofthematricesareincompa=bleforthematrixopera=on,anerrormessagewillresult.Forexample,*istheusualmatrixproduct,while.*istheelementbyelementproduct.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
The“matrixdivision”.IfAisaninver=blesquarematrixandbisacompa=blecolumn:
>>x=A\b%leftdivision,solutionofA*x=b>>x=b/A%rightdivision,solutionofx*A=b
MatrixBuildingFunc=ons
• Usedtobuildmatriceswithspecificproper=es
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
>>MB1=zeros(3)%builda3x3matrixwithall0>>MB2=[ones(3),zeros(3,2);zeros(2,3),eye(2)]%5x5matrix‐concatenation
MatrixandVectorsfunc=ons
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
%findthemaximumvalueina%matrix>>A=[723;452];>>max_vec=max(A)[753]>>max2=max(max_vec)7>>max2=max(max(A))7
%whenanarrayoperationis%appliedtoamatrix,itis%appliedtoeachcolumn,%theresultisanarray!
SubmatricesandColumnnota=on• Powerfulwaytoaccessdatastoredinmatrices.• TheelementinrowiandcolumnjofAisdenotedbyA(i,j).
• Thecolonoperator:isoneofthemostimportantMATLABoperators.
• Thesefeaturespermittominimizetheuseofloops(whichslowsMATLAB)andtomakecodesimple.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
>>a=[2:2:10];%createanarray>>A(1:3,3)%accesspartofamatrix>>A([24],:)%access2ndand4throw,allthecolumns>>A(:,2:end)%allrows,column2tothelast>>A(:,[245])=B(:,1:3)
Example:MagicMatrix• Knownforover4000years(foundinancientEgyptandIndia)wasseenfor
thefirst=meinEuropeanartintherenaissanceengravingMelencoliaIbytheGermanar=standamateurmathema=cianAlbrechtDürer.
• Knownasamagicsquare,wasbelievedhavingmagicalproper=es.Itdoesturnouttohavesomefascina=ngcharacteris=csworthexploring.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
OtherDataStructuresMatricescanbeusedtostorehomogenousdata,otherusefulstructuresare:
• Mul=dimensionalArrays• Structures• CellArrays• Func=onHandlers
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
Mul=dimensionalArrays
• Mul=dimensionalArrays– arrayswithmorethantwosubscripts;
>>B=rand(2,3,2);– usedtorepresentasequenceofmatrices,A(k),orsamplesofa=me‐dependentmatrix,A(t)• the(i,j)thelementofthekthmatrix
isdenotedbyA(i,j,k)
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
Ifwehaveamagicmatrixthatchangeover=me,wecanaccessthevaluesatacertain=mekusingaA(i,j,k)
StructuresStructuresandcellarrays,provideawaytostoredissimilartypesofdatainthesamearray.
• Structures– mul=dimensionalMATLABarrayswithelementsaccessedbytextualfielddesignators
>>my=[];>>my.age=35;>>my.country='Italy';my=age:35country:'Italy'
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
CellArrays• CellArray– acellarrayisacollec=onofcontainerscalledcellsinwhichyoucanstoredifferenttypesofdata
>>my={35,'Italy',[79111315]}my=[35]'Italy'[1x5double]
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
FlowControl
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
Matlabhasloopsandcondi=onals:for,while,if‐else(if),con=nue,break,try,catch.
Whenappliedtoscalars,arela=onisactually1or0dependingonwhethertherela=onistrueorfalse.
Whenappliedtomatricesofthesamesize,arela=onisamatrixof0'sand1'sdependingonthevalueoftherela=onbetweencorrespondingentries.
>>a=[2:2:10]246810>>a>600011
LoopsandCondi=onals
• Forloop:thesyntaxishighlightedintheboxes.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
x=[];n=5;fori=1:nx=[x,i^2];end
x=[];n=5;fori=1:nx(i)=i^2;end
x=[];n=5;fori=n:‐1:1x(i)=i^2;end
• If...else(elseif)...ifRELATIONstatementend
ifa==bstatementend
ifA~=Bstatementend
ifany(any(A~=B))statementend
aretheydifferent?why2“any”inthesecondone?
if(isequal(A,B))statementend
Loopsvs.Built‐inFunc=ons• WhenprogrammingwithMatlabyoushouldalwaystrytoavoidloopsandcondi=onalsandusebuilt‐infunc=ons.
• LoopsslowdownMatlabwhileBuilt‐infunc=onsarehighlyop=mized
• Eg.“for”vs“find”
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
random=rand(1,100000);%goal:createanewarraywithonlyelements>0.5
%solu=on1:forloopreal1=[];j=1;n=size(random,2)fori=1:nif(random(i)>0.5)real1(j)=random(i);j=j+1;endend
%solu=on2:built‐infunc=on(find)real2=[];real2=random(find(random(:)>0.5));
MUCHFASTER!
LogicalSubscrip=ng
• Anotherusefulnota=onisthelogicalsubscrip=ng.• Thelogicalvectorscreatedfromlogicalandrela=onalopera=onscanbeusedtoreferencesubarrays.
%extractasubarrayfromxwithnoNANsx=[2.11.71.61.5NaN1.9];y=x(isfinite(x))y=[2.11.71.61.51.9]
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
M‐files• WhenyouwriteaMATLABfunc=onorscript,yousaveittoafilecalledanM‐file(nameda\erits.mfileextension).
• TherearetwotypesofM‐files:scriptfilesandfunc=onfiles.
• M‐Filescanbeexecutedcallingtheirfilename.• Don’tforgettoaddthepathtoyourcodestotellMatlabwheretheyare!
• Alwaysusecomments(%)andgivemeaningful(notonlyforyou!)namestofunc=onsandvariables.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
M‐files:script• AscriptfileconsistsofasequenceofMATLABstatements.
• Ifthefilenameismyfile.mtheMATLABcommandmyfilewillcausethestatementsinthefiletobeexecuted.
• VariablesinascriptfileareglobalandwillchangethevalueofvariablesofthesamenameintheenvironmentofthecurrentMATLABsession.
• AnM‐filecanreferenceotherM‐files,includingreferencingitselfrecursively.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
M‐files:Func=ons• Func=onfilesactuallyprovideawaytoaddnewfunc=onalitytoMatlab.
• Youcancreatenewfunc=onsspecifictoyourproblemwhichwillthenhavethesamestatusasotherMATLABfunc=ons.
• VariablesinafuncNonfilearebydefaultlocal;itispossibletodeclarevariablesasglobal.
• Whenthefunc=onendsthelocalvariablesarenotavailableanymore.
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com
Beorganized...• SaveyourWork– save– diary
• DIARYFILENAMEcausesacopyofallsubsequentcommandwindowinputandmostoftheresul=ngcommandwindowoutputtobeappendedtoit
• WriteDocumenta=on– help
• CleanyourSpace– clc– clearall,clearname_var– closeall
Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com