getting started with matlab by hannah dotson, vikram kodibagkar laboratory
TRANSCRIPT
June11th,2010
SlidesContributedbyHannahDotsonSummerIntern2010KodibagkarMRLaboratoryLabmentor:SairamGeethanath,M.S.
¡ ThenameMATLABstandsformatrix
laboratory,andMATLABisan
interactivesystemwhosebasicdata
elementisanarraythatdoesnot
requiredimensioning.
¡ MATLABhastoolboxes,afamilyof
add-onapplication-specificsolutions
thatallowtheusertolearnandapplyspecializedtechnology.ToolboxesextendtheMATLAB
environmenttosolvecertaintypesofproblemsandexistformanyareas,includingsignal
processing,controlsystems,neuralnetworks,simulation,andmanyotherareas.
ImagefromMicrosoftClipart
¡ 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
¡ 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]
¡ MATLABusesthenormalarithmeticoperators
andprecedencerules,andhasanumberofstandard
elementarymathematicalfunctions.
¡ MATLABhas5functionsthatgeneratematrices,zeros,
ones,magic,rand,andrandn.Matricescanalsobeloaded
andconcatenated,androwsandcolumnscanbedeletedfromthem.
¡ MatricesinMATLABcanbeusedinbothlinearalgebraicandtwo-dimensionalarraytype
functions.Thereisalsoausefulfindfunctionthatdeterminestheindicesofarrayelements
thatmeetagivenlogicalcondition.
ThemagicfunctioninMATLAB[1]
¡ MATLABhasmanywaystoshowdata
graphically,andinteractivetools
allowsuchgraphstobemanipulated.
Graphscanbecreatedbyentering
commandsintotheCommandWindow
orinteractivelybyusingplottingtools.
¡ MATLABgraphsdisplayinaspecialwindowknownasafigure.Afteragraphis
created,thedatacanbeexplored,thegraphcomponentscanbeedited,the
graphcanbeannotated,andmanyotherfunctions.
AnexampleMATLABgraph/figure[1]
¡ Theplotfunctioncanbeusedtomakegraphs,andit
hasmanydifferentformsdependingontheinput
arguments,allowingtheusertocontrolmany
aspectsofthegraph,suchaslinetype,linecolor,
markertype,andmarkercolor.
¡ Thesubplotcommandcanbeusedtodisplaymultiple
plotsinthesamewindowbypartitioningthefigure
windowintoamatrixwherethedifferentplotsarecreated.
¡ Anidentifier,calledahandle,iscreatedwheneverMATLABcreatesagraphicsobjectandassignedto
theobject.Thishandlecanbeusedtoaccessanobject’spropertiesforbothsetandgetfunctions.
TheMATLABsubplotcommand[1]
¡ MATLABhaswaystocontrolflowofthe
programming,includingconditionalandloop
control.MATLABhasbothifelseandswitchcase
conditionalstructures,andforloopcontrol,
usesfor,while,continue,andbreak.
¡ MATLABalsohasthetrycatchforerrorcontrol,
aswellthereturncommandforprogramtermination.
¡ ThereareotherstructuresinMATLAB,includingmultidimensionalarrays,cell
arrays,charactersandtext,structures,anddynamicfieldnames.
MATLABcodeshowingtheuseofwhileandifelse[1]
¡ CommandsinMATLABcanbeenteredoneatatimeusingthecommandline,oraseriesofcommandsina
filecanbeexecuted.Thetwotypesofprograms,scripts,whichdonotacceptinputargumentsorreturn
outputarguments,andfunctions,whichcanacceptinputargumentsandreturnoutputarguments.
¡ Object-orientedprogramminginMATLABallowstheprogrammertocreatelargeapplicationsanddefine
complexdatastructures.FeaturetosupposeOOPincludesupportforvalueandhandle(reference)classes,
definitionofeventsandlisteners,classintrospection,andJIT/Acceleratorsupportforclassestoimprove
performance.
ThecodeofasampleMATLABfunction[1]
¡ Thetwobasicgoalsofdataanalysisare
describingthepatternsinthedatawith
simplemodelsthatleadtoaccuratepredictions
andunderstandingtherelationshipsamong
variablesthatleadtothemodel.Thisis
achievedbyfourbasiccomponents.
¡ First,thedataispreprocessed,whichincludes
loadingthedata,checkingforoutliers,
checkingformissingdata,andsmoothingandfilteringdata.
¡ Thenextstepistosummarizetheoveralllocation,scale,andshapeofadatasample,whichMATLAB
providesseveralfunctionsfor.
SampledataanalysisinMATLAB[1]
¡ MATLABcanalsobeusedinvisualizing
data,throughscatterplots,graphs,and
othertools.MATLABallowstheuserto
createboth2-Dand3-Dscatterplots,
aswellasscatterplotarrays,and
explorethedataingraphs.
¡ Modelingdatainthefinalcomponentofdataanalysis,andparametricmodelsallowthe
usertopredictwhatcomesnext,basedonthealreadyknowndata.MATLABhas
functionsforbothpolynomialandgenerallinearregression
A3DscatterplotinMATLAB[1]
¡ TheMATLABdesktophasmany
importantpartsandcanbecustomized
tofittheuser’spreference.The
CommandWindowallowstheuserto
entervariablesandrunfunctions,andthe
CommandHistoryallowstheuserto
viewandsearchforpreviouslyrun
statements,aswellascopyandexecuteselectedstatements.
¡ MATLABhasahelpfilecomparabletotheJavaAPI,anditisusefulforfindingmethodsormoredetails
aboutmethodsyouwishtoimplement.Inparticular,thedocandhelpcommandscanbeusefulin
learningaboutMATLABfunctions.
TheMATLABdesktop[1]
¡ TheMATLABWorkspaceBrowserallows
youtoaddvariablestotheworkspace.The
VariableEditorisusedtoviewandedita
visualrepresentationofworkspacevariables.
¡ MATLABhasfunctionstofindafile,change,
orrun,organizefiles,andensurethatMATLAB
canaccessafilesoitcanrunorload.
¡ TheEditorinMATLABisusedtocreateanddebugprogramsandtorunMATLABfunctions.It
providesagraphicaluserinterfacefortexteditinganddebuggingMATLABcode.For
MATLAB,codeanalysisincludesidentifyingerrorsbyunderliningcodeinred.
TheMATLABeditor,showingcodeanalysis[1]
¡ Digitalimageprocessingrefersto
processing,suchaschangingor
analyzing,digitalimagesusing
computers.Digitalimagesaremade
ofelements,usuallyreferredtoas
pixels.
¡ Imagingmachinescancovernearlytheentireelectromagneticspectrum,
allowingpeopletoimageobjectsorenergyinvisibletothehumaneye.ImagefromMicrosoftClipart
¡ 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]
¡ Animageisa2Dfunction,f(x,y),wherex
andyarespatialcoordinatesandthe
amplitudeoffatanypairofcoordinates
iscalledtheintensityoftheimageatthat
point.Graylevelreferstotheintensityof
monochromeimages,andcolorimages
areformedbyacombinationofindividual2Dimages.
¡ ImagescanbereadintoMATLABusingthecommandimreadanddisplayedusingthe
commandimshow.Imagescanalsobewrittentodiskusingthefunctionimwrite,and
imfinfocanreturndetailsaboutanimagefile.
AgrayscaleimageinMATLAB,showingpixelvalues[1]
¡ ThetoolboxforimagesinMATLABsupportsintensityimages,binaryimages,indexed
images,andRGBimages.Anintensityimageisadatamatrixwhosevalueshavebeen
scaledtorepresentintensities,andabinaryimageisalogicalarrayof0sand1s.
¡ MATLABhas10dataclasses.The8numericonesaredouble,uint8,uint16,uint32,int8,
int16,int32,andsingle.Thereisalsoacharacterclass,char,andalogicalclass,logical.
AbinaryimageinMATLAB,showingpixelvalues[1]
¡ 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]
¡ 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
¡ 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
¡ 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
1.MATLABDocumentation.TheMathWorks,Inc.2010.
2.Gonzalez,RafaelC.,Woods,RichardE.,andEddins,StevenL.DigitalImageProcessingUsingMATLAB.PearsonEducation,Inc.2004.
¡ *Note*:Images,unlessotherwisenoted,arefromtheMATLABDocumentationincludedwiththeMATLABprogram.