matlab - caltech astronomygeorge/aybi199/oldlectures/donalek_matlab1.pdf · • applicaon...

30
Matlab Ciro Donalek Ay/Bi 199ab: Methods of Computa=onal Sciences ‐ hAp://esci101.blogspot.com [email protected]

Upload: hakhue

Post on 30-Jun-2019

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

MatlabCiroDonalek

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com

[email protected]

Page 2: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 3: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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.

Page 4: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 5: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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/

Page 6: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

MatlabFamilyProducts•  Availablemanytoolboxesforspecificapplica=ons.

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com

Page 7: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 8: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 9: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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.

Page 10: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 11: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

Everythingisa...Matrix

•  IntheMATLABamatrixisarectangulararrayofnumbers.– scalarscanbeseenas1‐by‐1matrices;– array(vectors)arematriceswithjustoneroworonecolumn.

•  MATLABallowsyoutoworkwithen=rematricesquicklyandeasily.

•  Itisusuallybesttothinkofeverythingasamatrix.

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com

Page 12: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 13: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

EnteringMatrices

Basicconven=ons:

•  Separatetheelementsofarowwithblanksorcommas.

•  Useasemicolon;toindicatetheendofeachrow.

•  Surroundtheen=relistofelementswithsquarebrackets[].

>>A=[1,2,3;4,5,6]

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com

Page 14: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 15: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 16: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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!

Page 17: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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)

Page 18: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

Example:MagicMatrix•  Knownforover4000years(foundinancientEgyptandIndia)wasseenfor

thefirst=meinEuropeanartintherenaissanceengravingMelencoliaIbytheGermanar=standamateurmathema=cianAlbrechtDürer.

•  Knownasamagicsquare,wasbelievedhavingmagicalproper=es.Itdoesturnouttohavesomefascina=ngcharacteris=csworthexploring.

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com

Page 19: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

OtherDataStructuresMatricescanbeusedtostorehomogenousdata,otherusefulstructuresare:

• Mul=dimensionalArrays•  Structures•  CellArrays•  Func=onHandlers

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com

Page 20: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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)

Page 21: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

StructuresStructuresandcellarrays,provideawaytostoredissimilartypesofdatainthesamearray.

•  Structures– mul=dimensionalMATLABarrayswithelementsaccessedbytextualfielddesignators

>>my=[];>>my.age=35;>>my.country='Italy';my=age:35country:'Italy'

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com

Page 22: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

CellArrays•  CellArray–  acellarrayisacollec=onofcontainerscalledcellsinwhichyoucanstoredifferenttypesofdata

>>my={35,'Italy',[79111315]}my=[35]'Italy'[1x5double]

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com

Page 23: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 24: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 25: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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!

Page 26: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 27: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

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

Page 28: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

M‐files:script•  AscriptfileconsistsofasequenceofMATLABstatements.

•  Ifthefilenameismyfile.mtheMATLABcommandmyfilewillcausethestatementsinthefiletobeexecuted.

•  VariablesinascriptfileareglobalandwillchangethevalueofvariablesofthesamenameintheenvironmentofthecurrentMATLABsession.

•  AnM‐filecanreferenceotherM‐files,includingreferencingitselfrecursively.

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com

Page 29: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

M‐files:Func=ons•  Func=onfilesactuallyprovideawaytoaddnewfunc=onalitytoMatlab.

•  Youcancreatenewfunc=onsspecifictoyourproblemwhichwillthenhavethesamestatusasotherMATLABfunc=ons.

•  VariablesinafuncNonfilearebydefaultlocal;itispossibletodeclarevariablesasglobal.

•  Whenthefunc=onendsthelocalvariablesarenotavailableanymore.

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com

Page 30: Matlab - Caltech Astronomygeorge/aybi199/OldLectures/Donalek_Matlab1.pdf · • Applicaon Development, including Graphical User Interface building Ay/Bi ... Programming in Matlab

Beorganized...•  SaveyourWork–  save–  diary

•  DIARYFILENAMEcausesacopyofallsubsequentcommandwindowinputandmostoftheresul=ngcommandwindowoutputtobeappendedtoit

•  WriteDocumenta=on–  help

•  CleanyourSpace–  clc–  clearall,clearname_var–  closeall

Ay/Bi199ab:MethodsofComputa=onalSciences‐hAp://esci101.blogspot.com