22
June 11 th , 2010 Slides Contributed by Hannah Dotson Summer Intern 2010 Kodibagkar MR Laboratory Lab mentor: Sairam Geethanath, M.S.

Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

Embed Size (px)

Citation preview

Page 1: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

June11th,2010

SlidesContributedbyHannahDotsonSummerIntern2010KodibagkarMRLaboratoryLabmentor:SairamGeethanath,M.S.

Page 2: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  ThenameMATLABstandsformatrix

laboratory,andMATLABisan

interactivesystemwhosebasicdata

elementisanarraythatdoesnot

requiredimensioning.

¡  MATLABhastoolboxes,afamilyof

add-onapplication-specificsolutions

thatallowtheusertolearnandapplyspecializedtechnology.ToolboxesextendtheMATLAB

environmenttosolvecertaintypesofproblemsandexistformanyareas,includingsignal

processing,controlsystems,neuralnetworks,simulation,andmanyotherareas.

ImagefromMicrosoftClipart

Page 3: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  UsesforMATLABincludemathandcomputation,algorithm

development,dataacquisition,modeling,simulation,and

prototyping,dataanalysis,exploration,andvisualization,

scientificandengineeringgraphics,andapplicationdevelopment.

¡  MATLABusesahigh-performancelanguagefortechnical

computing.Theprogramintegratescomputation,visualization,

andprogramminginanenvironmentwhereproblemsand

solutionsareexpressedinfamiliarmathematicalnotation.

¡  TheMATLABprogramprovidesextensivedocumentation,inbothprintableandHTMLformat,tohelp

youlearnaboutanduseallofitsfeatures.ThereisreferencedocumentationforallMATLABfunctions

andtopics.

http://www.gtsav.gatech.edu/people/ffedele/cee3000/Fall08/CEE3000Fall08_files/matlab_logo.jpg

Page 4: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  Unlikeotherprogramminglanguages,MATLABallowsonetoworkwithentirematricesquickly

andeasilyandhasseveralwaystoentermatrices.Functionstoworkwithorcreatematrices

includesum,transpose,diag,andmagic,andthe:operatorisalsoimportant.

¡  NotypedeclarationsordimensionstatementsarerequiredforvariablesinMATLAB,and

numbersinconventionaldecimalnotation,scientificnotation,andimaginarynumbersare

allowed.

[1, 2, 3; 4, 5, 6; 7, 8, 9]

Page 5: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  MATLABusesthenormalarithmeticoperators

andprecedencerules,andhasanumberofstandard

elementarymathematicalfunctions.

¡  MATLABhas5functionsthatgeneratematrices,zeros,

ones,magic,rand,andrandn.Matricescanalsobeloaded

andconcatenated,androwsandcolumnscanbedeletedfromthem.

¡  MatricesinMATLABcanbeusedinbothlinearalgebraicandtwo-dimensionalarraytype

functions.Thereisalsoausefulfindfunctionthatdeterminestheindicesofarrayelements

thatmeetagivenlogicalcondition.

ThemagicfunctioninMATLAB[1]

Page 6: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  MATLABhasmanywaystoshowdata

graphically,andinteractivetools

allowsuchgraphstobemanipulated.

Graphscanbecreatedbyentering

commandsintotheCommandWindow

orinteractivelybyusingplottingtools.

¡  MATLABgraphsdisplayinaspecialwindowknownasafigure.Afteragraphis

created,thedatacanbeexplored,thegraphcomponentscanbeedited,the

graphcanbeannotated,andmanyotherfunctions.

AnexampleMATLABgraph/figure[1]

Page 7: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  Theplotfunctioncanbeusedtomakegraphs,andit

hasmanydifferentformsdependingontheinput

arguments,allowingtheusertocontrolmany

aspectsofthegraph,suchaslinetype,linecolor,

markertype,andmarkercolor.

¡  Thesubplotcommandcanbeusedtodisplaymultiple

plotsinthesamewindowbypartitioningthefigure

windowintoamatrixwherethedifferentplotsarecreated.

¡  Anidentifier,calledahandle,iscreatedwheneverMATLABcreatesagraphicsobjectandassignedto

theobject.Thishandlecanbeusedtoaccessanobject’spropertiesforbothsetandgetfunctions.

TheMATLABsubplotcommand[1]

Page 8: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  MATLABhaswaystocontrolflowofthe

programming,includingconditionalandloop

control.MATLABhasbothifelseandswitchcase

conditionalstructures,andforloopcontrol,

usesfor,while,continue,andbreak.

¡  MATLABalsohasthetrycatchforerrorcontrol,

aswellthereturncommandforprogramtermination.

¡  ThereareotherstructuresinMATLAB,includingmultidimensionalarrays,cell

arrays,charactersandtext,structures,anddynamicfieldnames.

MATLABcodeshowingtheuseofwhileandifelse[1]

Page 9: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  CommandsinMATLABcanbeenteredoneatatimeusingthecommandline,oraseriesofcommandsina

filecanbeexecuted.Thetwotypesofprograms,scripts,whichdonotacceptinputargumentsorreturn

outputarguments,andfunctions,whichcanacceptinputargumentsandreturnoutputarguments.

¡  Object-orientedprogramminginMATLABallowstheprogrammertocreatelargeapplicationsanddefine

complexdatastructures.FeaturetosupposeOOPincludesupportforvalueandhandle(reference)classes,

definitionofeventsandlisteners,classintrospection,andJIT/Acceleratorsupportforclassestoimprove

performance.

ThecodeofasampleMATLABfunction[1]

Page 10: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  Thetwobasicgoalsofdataanalysisare

describingthepatternsinthedatawith

simplemodelsthatleadtoaccuratepredictions

andunderstandingtherelationshipsamong

variablesthatleadtothemodel.Thisis

achievedbyfourbasiccomponents.

¡  First,thedataispreprocessed,whichincludes

loadingthedata,checkingforoutliers,

checkingformissingdata,andsmoothingandfilteringdata.

¡  Thenextstepistosummarizetheoveralllocation,scale,andshapeofadatasample,whichMATLAB

providesseveralfunctionsfor.

SampledataanalysisinMATLAB[1]

Page 11: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  MATLABcanalsobeusedinvisualizing

data,throughscatterplots,graphs,and

othertools.MATLABallowstheuserto

createboth2-Dand3-Dscatterplots,

aswellasscatterplotarrays,and

explorethedataingraphs.

¡  Modelingdatainthefinalcomponentofdataanalysis,andparametricmodelsallowthe

usertopredictwhatcomesnext,basedonthealreadyknowndata.MATLABhas

functionsforbothpolynomialandgenerallinearregression

A3DscatterplotinMATLAB[1]

Page 12: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  TheMATLABdesktophasmany

importantpartsandcanbecustomized

tofittheuser’spreference.The

CommandWindowallowstheuserto

entervariablesandrunfunctions,andthe

CommandHistoryallowstheuserto

viewandsearchforpreviouslyrun

statements,aswellascopyandexecuteselectedstatements.

¡  MATLABhasahelpfilecomparabletotheJavaAPI,anditisusefulforfindingmethodsormoredetails

aboutmethodsyouwishtoimplement.Inparticular,thedocandhelpcommandscanbeusefulin

learningaboutMATLABfunctions.

TheMATLABdesktop[1]

Page 13: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  TheMATLABWorkspaceBrowserallows

youtoaddvariablestotheworkspace.The

VariableEditorisusedtoviewandedita

visualrepresentationofworkspacevariables.

¡  MATLABhasfunctionstofindafile,change,

orrun,organizefiles,andensurethatMATLAB

canaccessafilesoitcanrunorload.

¡  TheEditorinMATLABisusedtocreateanddebugprogramsandtorunMATLABfunctions.It

providesagraphicaluserinterfacefortexteditinganddebuggingMATLABcode.For

MATLAB,codeanalysisincludesidentifyingerrorsbyunderliningcodeinred.

TheMATLABeditor,showingcodeanalysis[1]

Page 14: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  Digitalimageprocessingrefersto

processing,suchaschangingor

analyzing,digitalimagesusing

computers.Digitalimagesaremade

ofelements,usuallyreferredtoas

pixels.

¡  Imagingmachinescancovernearlytheentireelectromagneticspectrum,

allowingpeopletoimageobjectsorenergyinvisibletothehumaneye.ImagefromMicrosoftClipart

Page 15: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  Imageprocessingcanbethoughtofinthreeparts.First,

low-levelprocessinginvolvesoperationssuchasreducing

noiseorcontrastenhancement,anditisidentifiedbythefact

thatbothitsinputsandoutputsareimages.

¡  Mid-levelprocessingincludessegmentationofanimageand

clarificationofobjectsinanimages.Theseprocesseshavean

imageasaninput,butanoutputthatisgenerallyextracted

fromtheimage.

¡  Lastly,higher-levelprocessingincludes“makingsense”of

whatcanbeseeninanimage,overlappingwithimage

analysis.

Anexampleofdigitalimageprocessing,removingnoise,usingMATLAB[1]

Page 16: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  Animageisa2Dfunction,f(x,y),wherex

andyarespatialcoordinatesandthe

amplitudeoffatanypairofcoordinates

iscalledtheintensityoftheimageatthat

point.Graylevelreferstotheintensityof

monochromeimages,andcolorimages

areformedbyacombinationofindividual2Dimages.

¡  ImagescanbereadintoMATLABusingthecommandimreadanddisplayedusingthe

commandimshow.Imagescanalsobewrittentodiskusingthefunctionimwrite,and

imfinfocanreturndetailsaboutanimagefile.

AgrayscaleimageinMATLAB,showingpixelvalues[1]

Page 17: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  ThetoolboxforimagesinMATLABsupportsintensityimages,binaryimages,indexed

images,andRGBimages.Anintensityimageisadatamatrixwhosevalueshavebeen

scaledtorepresentintensities,andabinaryimageisalogicalarrayof0sand1s.

¡  MATLABhas10dataclasses.The8numericonesaredouble,uint8,uint16,uint32,int8,

int16,int32,andsingle.Thereisalsoacharacterclass,char,andalogicalclass,logical.

AbinaryimageinMATLAB,showingpixelvalues[1]

Page 18: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  Commandstocreatematricesincludezeros(M,N),

whichgeneratesanMxNmatrixof0sofclass

double,ones(M,N),whichgeneratesanMxN

matrixof1sofclassdouble,magic(M),which

generatesanMxMmagicsquare,rand(M,N),

whichgeneratesanMxNmatrixwhoseentriesareuniformlydistributedrandom

numbersintheinterval[0,1],andrandn(M,N),whichgeneratesaMxNmatrix

whosenumbersarenormallydistributedrandomnumberswithameanof0and

varianceof1.

A“MagicSquare”Matrix[1]

Page 19: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  helpfunctionname:displaysabriefdescriptionandthesyntaxforfunctionnameintheCommandWindow

¡  docfunctionname:displaysthereferencepageforfunctionNameintheHelpbrowser-similartotheJavaAPI

¡  clc:clearsallinputandoutputfromtheCommandWindowdisplay,givingyoua"cleanscreen"

¡  clearall:removesallvariablesfromtheworkspace,releasingthemfromsystemmemory

¡  closeall:deletesallfigureswhosehandlesarenothidden¡  tic;any_statements;toc:measuresthetimeittakestheMATLAB

softwaretoexecutetheoneormorelinesofMATLABcodeshownhereasany_statements

¡  function[out1,out2,...]=myfun(in1,in2,...):declaresthefunctionmyfun,anditsinputsandoutputs-similartocreatingamethodinJava

¡  disp:displaysanarray.IfXcontainsatextstring,thestringisdisplayed.¡  dbstop:temporarilystopstheexecutingmfile,puttingMATLABindebug

mode¡  figure:Createafiguregraphicsobject

Page 20: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  imread(filename):readsagrayscaleorcolorimagefromthefilespecifiedbythestringfilename

¡  imshow(I):displaysthegrayscaleortruecolorimageI¡  subplot:dividesthecurrentfigureintorectangularpanesthatare

numberedrow-wise¡  squeeze:returnsanarrayBwiththesameelementsasA,butwithall

singletondimensionsremoved.Asingletondimensionisanydimensionforwhichsize(A,dim)=1.

¡  phantom:generatesanimageofaheadphantomthatcanbeusedtotestthenumericalaccuracyoftwo-dimensionalreconstructionalgorithms

¡  colorbar:functiondisplaysthecurrentcolormapinthecurrentfigureandresizesthecurrentaxestoaccommodatethecolorbar

¡  colormap:setsandgetscurrentcolormap¡  drawnow:causesfigurewindowsandtheirchildrentoupdate,and

flushesthesystemeventqueue.Anycallbacksgeneratedbyincomingevents(e.g.,mouseorkeyevents)aredispatchedbeforedrawnowreturns.

¡  avifile:createsnewAudio/VideoInterleaved(AVI)file

Page 21: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

¡  plot(Y):plotsthecolumnsofYversustheindexofeachvaluewhenYisarealnumber

¡  plot(X,Y):plotseachvectorYversusvectorXonthesameaxes¡  set:setHandleGraphicsobjectproperties,suchasx-ticksona

graph(seedocplotformoreuses)¡  hold:determineswhethernewgraphicsobjectsareaddedtothe

graphorreplaceobjectsinthegraph.¡  title:addsatitletocurrentaxes¡  axis([xminxmaxyminymax]):setsthelimitsforthex-and

y-axisofthecurrentaxes.¡  legend:placesalegendonvarioustypesofgraphs(lineplots,

bargraphs,piecharts,etc.).Foreachlineplotted,thelegendshowsasampleofthelinetype,markersymbol,andcolorbesidethetextlabelyouspecify

Page 22: Getting started with Matlab by Hannah Dotson, Vikram Kodibagkar laboratory

1.MATLABDocumentation.TheMathWorks,Inc.2010.

2.Gonzalez,RafaelC.,Woods,RichardE.,andEddins,StevenL.DigitalImageProcessingUsingMATLAB.PearsonEducation,Inc.2004.

¡  *Note*:Images,unlessotherwisenoted,arefromtheMATLABDocumentationincludedwiththeMATLABprogram.