Matlab - California Institute of Technology · Programming in Matlab • The Language – The...

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

Transcript of Matlab - California Institute of Technology · Programming in Matlab • The Language – The...

Page 1: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

MatlabCiroDonalek

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

[email protected]

Page 2: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Summary•  Introduc=ontoMatlab•  ProgramminginMatlab–  datatypes,variables–  loopsvsBuilt‐InFunc=ons

•  MatrixandArrayOpera=ons–  SubmatricesandColumnNota=on

•  M‐Files–  script,func=ons

•  Visualiza=on•  Performanceevalua=on•  AdvancedUse–  Compiler,Databaseconnec=on,HowtobuildaGUI...

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

Page 3: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

MatlabFamilyProducts•  Availablemanytoolboxesforspecificapplica=ons.

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

Page 7: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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

–  typeiskeywordtoseethelistofkeywordsinMatlab

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

Page 9: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Everythingisa...Matrix

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

•  MATLABallowsyoutoworkwithen=rematricesquicklyandeasily.

•  Itisusuallybesttothinkofeverythingasamatrix.

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

Page 12: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

OtherDataStructuresMatricescanbeusedtostorehomogenousdata,otherusefulstructuresare:

•  Mul=dimensionalArrays•  Structures•  CellArrays•  ArraysandStructures•  Func=onHandles

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

Page 20: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

CellArrays•  CellArray–  acellarrayisacollec=onofcontainerscalledcellsinwhichyoucanstoredifferenttypesofdata

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

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

Page 23: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

ArraysandStructures

•  StructuresofArraysvs.ArraysofStructures

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

%StructuresofArraysa.x=1:10;a.y=sin(a.x);

Eachfieldisanarray.Goodwaytokeepdatathatarerelatedtogether.Easytopassinonestructurewhenusingfunc=ons.

%ArraysofStructurespeople(1).name='Ciro';people(1).age=35;people(1).country='Italy'people(2).name='Matusalem';people(2).alt_name='Methuselah'people(2).age=969;people(2).country='Unknown';

Eachelementofthearrayisastructure.Usefulwhenyouhavemul=plecopiesofthesamedataset:youcanaccesseasilyapar=cularrecord.

Page 24: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Func=onHandle•  Afunc=onhandleisacallableassocia=ontoaMATLABfunc=on:

h=@func=onname

•  Withfunc=onhandles,youcan:– passafunc=ontoanotherfunc=on– callfunc=onsoutsideoftheirnormalscope

– savethehandleinaMAT‐filetobeusedinalaterMATLABsession

– useanonymousfunc=ons

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

Page 25: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Func=onHandles:Examples

•  associateafunc=onhandlertoafunc=onmy_f=@stat

•  anonymousfunc=ons

my_sqr=@(x)x.^2;

•  arrayoffunc=onhandlestrigFun={@sin,@cos,@tan};%cellarray

plot(trigFun{2}(‐pi:0.01:pi))

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

Page 26: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 27: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 28: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

AvoidandSpeedUpLoops

•  Built‐InFunc=ons•  Vectoriza=on•  Pre‐Alloca=on

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

Page 29: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 30: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Vectoriza=on

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

%VectorizingadoubleFORloopthatcreatesa%matrixbycomputation.%ReplacewithelementbyelementmatrixoperationsA=rand(1000);B=rand(1000);

ticforj=1:1000fork=1:1000;X1(j,k)=sqrt(A(j,k))*B(j,k);endendsum1=sum(sum(X1))toc

%usingvectorization‐>MUCHFASTER!!!ticX2=sqrt(A).*B;sum2=sum(sum(X2))toc

Page 31: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Prealloca=on•  Ifyoucannotvectorizeapieceofcode,youcanmakeyourfor

loopsgofasterbyprealloca=nganyarraysinwhichoutputresultsarestored.

•  Withouttheprealloca=ontheMATLABinterpreterenlargestheoutputvectorbyoneelementeach=methroughtheloop.–  Vectorprealloca=oneliminatesthisstepandresultsinfasterexecu=on.

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

%usingpreallocationA=rand(1000);B=rand(1000);ticX3=zeros(1000,1000);forj=1:1000fork=1:1000;X3(j,k)=sqrt(A(j,k))*B(j,k);endendsum3=sum(sum(X3))toc

Page 32: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 33: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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 34: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

M‐files:script•  AscriptfileconsistsofasequenceofMATLABstatements.

•  Ifthefilenameismyfile.mtheMATLABcommandmyfilewillcausethestatementsinthefiletobeexecuted.

•  VariablesinascriptfileareglobalandwillchangethevalueofvariablesofthesamenameintheenvironmentofthecurrentMATLABsession.

•  AnM‐filecanreferenceotherM‐files,includingreferencingitselfrecursively.

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

Page 35: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

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

•  Youcancreatenewfunc=onsspecifictoyourproblemwhichwillthenhavethesamestatusasotherMATLABfunc=ons.

•  VariablesinafuncNonfilearebydefaultlocal;itispossibletodeclarevariablesasglobal.

•  Whenthefunc=onendsthelocalvariablesarenotavailableanymore.

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

Page 36: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Beorganized...•  SaveyourWork–  save–  diary

•  DIARYFILENAMEcausesacopyofallsubsequentcommandwindowinputandmostoftheresul=ngcommandwindowoutputtobeappendedtoit

•  WriteDocumenta=on–  help

•  CleanyourSpace–  clc–  clearall,clearname_var–  closeall

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

Page 37: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

FiguresandPlots•  Matlabgivesaveryeasywaytogenerateandannotatemanykinds

of2‐Dand3‐Dplots.

•  AfigureisaMATLABwindowthatcontainsgraphicdisplays(usuallydataplots)andUIcomponents.–  bydefault,figurewindowsareresizableandincludepull‐downmenus

andtoolbars–  youcreatefiguresexplicitlywiththefigurefunc=on,andimplicitly

wheneveryouplotgraphicsandnofigureisac=ve

•  Aplotisanygraphicdisplayyoucancreatewithinafigurewindow–  eachplotiscreatedwithina2‐Dora3‐Ddataspacecalledanaxes.–  candisplaytabulardata,geometricobjects,surfaceandimageobjects,

andannota=onssuchas=tles,legends,andcolorbars.–  figurescancontainanynumberofplots.

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

Page 38: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

AnatomyofaGraph

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

x=[0:.2:20];y=sin(x)./sqrt(x+1);y(2,:)=sin(x/2)./sqrt(x+1);y(3,:)=sin(x/3)./sqrt(x+1);plot(x,y)legend('s1','s2','s3');

Page 39: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Interac=vePlo[ng

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

PlotProper=escanbeset:‐viascript,arguments‐usingtheinterac=veplot

Page 40: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Subplots•  SUBPLOTCreateaxesin=ledposi=ons.– H=SUBPLOT(m,n,p)breakstheFigureWindowintoanm‐by‐nmatrixofsmallaxes,selectsthep‐thaxesforthecurrentplot,andreturnstheaxishandle.

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

Page 41: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

2D‐Plots

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

Page 42: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Represen=ngamatrixasasurface

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

%considerthesin(r)/r[X,Y]=meshgrid(‐8:.5:8);

%ThematrixRcontainsthedistance%fromthecenterofthematrix%AddingepspreventsthedividebyzeroR=sqrt(X.^2+Y.^2)+eps;%valuesofthesincfunctionZ=sin(R)./R;mesh(X,Y,Z)

%lightsandviewadjustmentfigure;surf(X,Y,Z,'FaceColor','interp',...'EdgeColor','none',...'FaceLighting','phong')daspect([551])axistightview(‐50,30)camlightleft

Themeshgridfunc=ontransformsthedomainspecifiedbytwovectors,xandy,intomatricesXandY.TherowsofXarecopiesofthevectorxandthecolumnsofYarecopiesofthevectory.Thesematricescanbeusedtoevaluatefunc=onsoftwovariables:

Page 43: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

3D‐Plots

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

Page 44: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

GraphicalUserInterface•  GUIDE:GraphicalUserInterfaceDevelopmentEnvironment– providesasetoftoolsforcrea=ngGUIs– simplifytheprocesstodesignandbuildGUI– hasmanycomponents:panels,buAons,textfields,sliders,menus...(draganddrop)

– automa=callygeneratesanM‐filethatcontrolshowtheGUIoperates.•  TheM‐fileini=alizestheGUIandcontainsaframeworkforthemostcommonlyusedcallbacksforeachcomponent–  commandexecutedwhenauserclicksaGUIcomponent

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

Page 45: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

StartGUIDE

•  TostartGUIDE:guide

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

Page 46: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

AddingElements

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

Page 47: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

ProgrammingaGUI•  A\erlayingouttheGUIandse[ngcomponentproper=es,thenextstepistoprogramtheGUI.

•  YouprogramtheGUIbycodingoneormorecallbacksforeachofitscomponents.

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

Page 48: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

AmoreadvancedGUI

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

Page 49: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

CoinCount

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

%requirestheImageProcessingToolboxI=imread('coins.png');%readanimageimshow(I)%showtheimageBW=im2bw(I);%converttheimageinB/Wfigure,imshow(BW)%showtheB/Wimagedim=size(BW)%sizeoftheimageinpixelscol=round(dim(2)/2)‐90;%determinethestartinglocationrow=min(find(BW(:,col)))%fortheboundarytracingboundary=bwtraceboundary(BW,[row,col],'N');

%bwboundaries:bydefaultfindstheboundariesofallobjectsinanimage%includingobjectsinsideotherobjects.%Inthebinaryimageusedinthisexample,someofthecoinscontain%blackareasthatbwboundariesinterpretsasseparateobjects.%Toensurethatbwboundariesonlytracesthecoins,%useimfilltofilltheareainsideeachcoin.

BW_filled=imfill(BW,'holes');boundaries=bwboundaries(BW_filled);fprintf('Numberofcoins:%d\n',size(boundaries,1));

Page 50: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Performances:evalua=on•  AgoodfirststeptospeedingupyourprogramsistofindoutwheretheboAlenecksare.

•  StopwatchTimerFunc=on–  togetanideaonhowlongtheprogramtakestorun– =c,toc

•  >>tic,rand(100000,1),toc•  >>tic,rand(100000,1);,toc

– measuring"small"programs•  runtheprogramrepeatedlyinaloop•  averagetofindthe=meforasinglerun

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

Page 51: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

ProfilerandCodeAnalyzer•  TheM‐FileProfilerU=lity–  graphicaluserinterfacethatshowsyouwhereyourprogramisspendingits=meduringexecu=on.

–  helpyoutodeterminewhereyoucanmodifyyourcodetomakeperformanceimprovements

–  tostarttheProfiler,youcantype•  >>profileviewer•  orselectDesktop>ProfilerintheMATLABCommand

•  TheM‐LintCodeAnalyzer–  checksyourcodeforproblemsandrecommendsmodifica=onstomaximizeperformanceandmaintainability•  >>mlintmyfile

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

Page 52: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

ImprovingPerformances•  Techniquestoimproveperformances– vectorizingloops– prealloca=ngarrays– mul=threading– parallelfor–  func=onsarefasterthanscript– avoidlargebackgroundprocesses–  ...

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

Page 53: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

OtherusefulToolboxes•  MatlabCompiler– cancompileM‐files,MEX‐filesorotherMATLABcode– cangenerate:

•  standaloneapplica=onsonUNIX,Windows,Mac•  CandC++sharedlibraries

•  DatabaseToolbox– enablestoexchangedatawithandanyODBC/JDBC‐compliantdatabase

– VisualQueryBuilder:allowstoquerystoreddatawithoutneedingtolearnSQL

•  ParallelToolbox•  NeuralNetworkToolbox

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

Page 54: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

ThirdPartyToolboxes•  Therearemanythirdpartytoolboxes,mostofthemcanbedownloadedforfree.

– Netlab:NeuralNetworksToolbox•  hAp://www.ncrg.aston.ac.uk/netlab/index.php

– SOM:SelfOrganizingMapsToolbox•  hAp://www.cis.hut.fi/projects/somtoolbox/

– BNT:BayesianNetworksToolbox•  hAp://www.cs.ubc.ca/~murphyk/So\ware/BNT/bnt.html

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

Page 55: Matlab - California Institute of Technology · Programming in Matlab • The Language – The MATLAB language is a high‐level matrix oriented language with: • control flow statements

Sendyourcomments...

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