Geology & Geophysics Matlab Tutorial PDF
Geology & Geophysics Matlab Tutorial PDF
Geology & Geophysics Matlab Tutorial PDF
G&GMatlabTutorial
OriginalversionfromGeology392tutorialithasnowbeenheavilymodified.Seetheendforcurrentmaintainer.
PlotoftheMatlabpeaks()functionasamplefunctionfor3dgraphicsbuiltfromtranslatedandscaled
Gaussians.
GettingStarted
Ingeneral,Matlabisrunbyselectingtheapplicationfromamenu,ortypingmatlabatthecommandlineprompt
inaUNIXenvironment.Oncerunning,Matlabisitselfacommandlineprogram,whereinyouwillbegivena
prompttotypeinspecificcommands.
Youshouldseeagraphicswindowflashuponthescreenandthendisappear.Ifso,youareallsetotherwiseyou
needtocheckthatyouhavesetyourdisplayvariablesproperly.Ifyoucan'tgetthegraphicstoappearonthe
screen,Matlabshouldwork,butwithoutanyplotting.
Toseethegraphicswindow,youjustneedtoplotsomething.Trytyping
>>plot(1:0.5:5)
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 1/16
13/02/2017 Geology&GeophysicsMatlabTutorial
whichwillplotthenumbers1to5(countingby0.5)bytheirindex(1to9).Asyou'llseelater,thecolon(:)isa
shorthandforcreatingavectorofnumbers.YouwilluseitalotinMatlab.
WhatisMatlab?
Matlabisaprogramfordoingscientificcalculationsusingmatrices.Thematrixisthebasicdatatypeofmatlab,
anditmayberealorcomplex.Matlabonlyusesdoubleprecisionfloatingpointnumberstherearenointeger
matrices.Youcanalsousescalars(1x1matrices)orvectors(nx1or1xnmatrices).WhatmakesMatlabvery
powerfulisthatyoucanperformoperationsonwholevectorsormatricesatonetime,withouthavingtoloop
througheachelement.Matlabisalsoquitegoodatplottingdata(in2and3d),whichmakesitusefulfor
plottingdatageneratedelsewhere.
Inthistutorial,we'llgooversomeofthebasiccommands,howtoreadindata,howtosavedata,howtoplot
data,andhowtocreatesimpleprograms,calledmfiles.
GettingHelpinMatlab
IfyougetstuckorjustneedmoreinformationaboutMatlab,thereareanumberofdifferentresources.The
easiestonetouseisbuiltintoMatlabitself.Bytypinghelporhelpcommand,youcangetadescriptionofa
commandorgroupofcommands.Trytyping
>>helpgraph2d
Thisgivesyoualistofallofthe2dimensionalplottingfunctionsavailable.Anotherhelpfulcommandisthe
lookforcommand.Bytypinglookforkeyword,youwillgetalistofallcommandsrelatedtokeyword,evenif
youaren'tsureoftheexactfunctionname.
Therearealsoanumberofbooks,includingtheMatlabmanualandGettingStartedinMatlabbyRudraPratap.
TheMathworks(developersofMatlab)WWWsite,http://www.mathworks.com,hasextensivedocumentation
available(underSupport).ThedocumentationforMatlab(butnotthetoolboxesorotherMathworksproducts)is
availablehere.Foruserswhowishtokillaforestoftreesforpapermanuals,theyareavailablefororderfrom
Mathworks,orasPDFfilesonthewebhere.
DealingWithVariables
Here'sashorttutorialonworkingwithvariables,takenfromthebook,GettingStartedinMatlab.Itishighly
recommendedthatyouobtainthisbookasitwillmakeyourlifeinMatlabeasier.VariablesinMatlabcanhave
anyname,butifthevariablehasthesamenameasafunction,thatfunctionwillbeunavailablewhilethe
variableexists.TrytypingthefollowingintoMatlab:
>>2+2 %Addtwonumbers
%
ans= %Matlabuses'ans'if
%thereisnovariable
4 %assignment(lvalue)
>>x=2+2 %Assignstheresult
%tovariable'x'
x= %anddisplaysthe
%valueof'x'
4 %
>>y=2^2+log(pi)*sin(x); %Thesemicolonat
>>y %theendsuppressesoutput
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 2/16
13/02/2017 Geology&GeophysicsMatlabTutorial
%Toseethevalueofa
y= %variable,enterjustits'
%name
3.1337
>>theta=acos(1) %Assignarccos(1)totheta
%Matlabusesradianforall
theta= %trigfunctions
3.1416
>>thetapi %Notethatpiisbuiltinto
%Matlab,andmoreprecision
ans= %iskeptinternallythanis
%printedonthescreen
0
CreatingandWorkingWithMatrices
InMatlab,thereareanumberofwaystocreatematrices.First,let'slookathowtogeneratevectors(callthemx
andy),whichare1xNmatrices.Wewillmakexgofrom0to3*pi.
>>x=0:0.1:3*pi; %Createvectorxfrom0to3*piin
%incrementsof0.1
%But,couldalsouse:
>>x=linspace(0,3*pi,100); %Createvectorxfrom0to3*piwith
%100stepsexactly
>>beta=0.5; %Createconstantbetaforerrorfunction
>>y=beta*erf(x/5); %Computeerf()foreachxvalue,and
%assigntoayvalue
%Notethatthereisnoloophere,but
%ynowhasasmanyentriesasx!
>>plot(x,y) %Plotxvs.ywithaline
Theplotshouldlooksomethinglikethis.
Now,let'strymakingtruetwodimensionalmatrices(MxN)startwitha3x3matrixtypedonthecommandline:
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 3/16
13/02/2017 Geology&GeophysicsMatlabTutorial
>>x=[147;258;369]; %semicolonsdenotechangesof
%row
>>x=[1,4,7 %Matlab'scommandlineknows
2,5,8 %thematrixisnotfinished
3,6,9]; %untiltheclosing']'
Inanycase,theresultisthesame,thefollowing3x3matrixstoredasthevariablex:
>>x %Displaythecurrentvalueofx
x=
147
258
369
Youshouldnoticethatsquarebrackets([])enclosethematrix,spacesorcommas(,)denoteelementswithina
row,andeitherasemicolon(;)orahardreturndenoterows.
Matlabalsohasfunctionstoproducematricesofzerosandonesofaspecifiedsize:
>>zeros([33]) %Producematrixofallzeros,
%sizeof3x3
ans=
000
000
000
>>zeros(3,3) %Alternatesizeformatofabove
ans=
000
000
000
>>zeros(2) %Matrixofzeros,size2x2
ans=
00
00
>>zeros([12]) %Rowvectorofzeros,2long
ans=
00
>>zeros([21]) %Columnvectorofzeros,2long
ans=
0
0
>>ones(2,2) %Sameaszeros(),butmatrixfilledwith1
ans=
11
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 4/16
13/02/2017 Geology&GeophysicsMatlabTutorial
11
Toaccessmatrixelements,specifytherowsandcolumnsweareinterestedin.Rememberhowweusedthe
colon(:)tofillinnumberswhenweplottednumbersfrom1to5inthefirstsection?Wewillusethatagain.The
syntaxisx(row,col)so,forexample,ifwewantthetoassigntheelementinthethirdrow,firstcolumntothe
variabley,wetype:
>>y=x(3,1); %Assignrow3,col1elementofxtoy
Tospecifyanentireroworcolumn,useacolon(:)inplaceoftheroworcolumnnumber.So,ifwewantthe
entiresecondcolumn,wewouldtype:
>>y=x(:,2); %Assignallrows,col2elementstoy
Nowlet'stryashortexercisetousematricesandmatrixoperations.
1.Createavectoroftheintegersfrom1to5andnameita.
2.Add1toalltheelementsofa,andstoreina.
3.Createavectoroftheintegersfrom5to1andnameitb.
4.Addatobandstoretheresultinc.
Hereisatranscript(diary)ofamatlabsessionimplementingtheexercise:
>>a=1:5; %vectorof1to5,increment1
>>a=a+1 %add1toallelementsofa
a=
23456
>>b=5:1:1 %vectorof5to1,increment1
b=
54321
>>c=a+b %addaandb,storeinc
c=
77777
Notethatallvectorsusedsofarhavebeenrowvectorsthevectorisarowfromamatrix(onerow,many
columns).Therearealsocolumnvectors,whicharedisplayedvertically(manyrows,onecolumn).Totransform
arowvectortoacolumnvector(orback),usethetransposeoperationinMatlab,thisisdenotedby'afterthe
vector(ormatrix)name.
>>a'
ans=
2
3
4
5
6
Matlab,beingfocusedonmatrixoperations,alwaysassumesoperationsarematrixoperationsunlesstold
otherwise.Intheexerciseabove,weaddedascalartoamatrix,whichisthesameasaddingascalartoevery
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 5/16
13/02/2017 Geology&GeophysicsMatlabTutorial
elementofthematrix.Ingeneral,though,Matlabwilldomatrixaddition,multiplication,division,etc.
TomakeMatlabapplyanoperationtoeachelementindividually(ratherthanusematrixoperations),usea.
(period)beforetheoperatorforexample,tosquareeachelementofavector,weuse:
>>a=1:5;
>>a.*a %the.makesMatlabapplythe*
%toeachelementasasetofscalar
ans= %operations,NOTmatrixmultiplication
1491625
Ifthereisno.,Matlabassumestheintentisamatrixoperation,whichwon'tworkfortworowvectors:
>>a*a
???Errorusing==>*
Innermatrixdimensionsmustagree.
Iftheintentreallyistodoamatrixmultiplicationofabya,weneedtotakethetransposeofthesecondvector:
>>a*a'
ans=
55
Sinceaisa1x5vector,a'(transposeofa)isa5x1vector.Whenmultiplied,theresultisa1x1vector,whichisa
scalar,asseenhere.
Keepingtrackofmatrixdimensionscanbedifficult,butisextremelyimportant.Fortunately,Matlabwill
normallyproduceerrorswhenyourcodetriestodosomethingmathematicallyincorrect.
AdvancedMatrixIndexingskipandcomebackifdesired
Matlabhasaverygeneralindexingability,whichcanmakecodethatiscompactandefficient,butless
transparent.Ingeneral,anywhereyoucanindexamatrixwithasinglenumber(orsetofnumbers),youcanalso
indexwithavectorormatrix.Someexamples:
EDU>>a=[1:3;4:6;7:9]%Create3x3matrix
a=
123
456
789
EDU>>a(:)%Accessmatrixasavector.
%Notethattheelementsaretaken
ans=%fromeachcolumnfirst,theneach
%row.Thisformatallowsthetreatment
1%ofanymultidimensionalarrayasa
4%vector,whichcanbeusefulforsome
7%functioncalls.
2%3+dimensionalarrayswilltakeelements
5%firstfromthelastdimension,working
8%backtothefirstdimension!
3
6
9
EDU>>b=[1:10].^2
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 6/16
13/02/2017 Geology&GeophysicsMatlabTutorial
b=
149162536496481100
EDU>>b(a)%Accesselementsofbusingvaluesofa.
%Notethattheresultisamatrixwiththe
ans=%sameshapeasa,butwithvaluestakenfrom
%b;theentriesofaareusedasindexes
149%intothevectorb.Matlabwillproducean
162536%errorifanyindexfromaisoutsidethe
496481%boundsofb.
EDU>>a%Reminderofentriesofmatrixa
a=
123
456
789
EDU>>b=flipud(a)
b=
789
456
123
EDU>>b(a)%Accesselementsofbusingvaluesofa.
%Notethattheelementsweretakenin
ans=%columnorder(elements13arethefirst
%column).ThiscomesfromMatlabtreating
741%basavectorfortheindexingoperation,
852%withtheresultingvectorreshapedtothe
963%sizeofa.
TheseexamplesarealldesignedtoshowhowMatlabstoresandretrievesinformationinarrays.Matlabstores
allarraysasalongvectorinmemory,regardlessofthenumberofdimensions.Amultidimensionalarray(a
matrix)isstoredasavector,withadditionalinformationonhowmanyrowsandcolumnsareinthematrix,so
Matlabcanquicklyaccessanyelementusing(row,column)indexing.Thetranslationfora2Dmatrix(nrxnc
elements)issimple:
A(i,j)==A(j*nr+i)
wherenristhenumberofrowsinthematrix.A3Darray(n1xn2xn3elements)issimilar:
A(i,j,k)==A((k*n1*n2)+(j*n2)+i)
wheren1isthestrideforthelastdimension,andn2isthestridefortheseconddimension.
Giventhismemorylayoutforamultidimensionalmatrix,itisclearwhyaccessingthematrixasavector(using
theA(:)notation)resultsinavectorwithcolumnsattachedendtoendMatlabisstartingatthefirstelement
andreadingstraightthroughuntiltheend.Thissortofindexing,onceunderstood,canmakesomeveryefficient
algorithms.Forexample,translatinggrayscalevaluesinanimagefromonescaletoanother:
EDU>>A=floor(rand(10)*255)%Createrandom10x10matrix
%of8bitgrayscalevalues
A=%[0255].
36713717318211192118466
731921581849233169233127221
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 7/16
13/02/2017 Geology&GeophysicsMatlabTutorial
208168174189628225581076
2515417237020769219168132
41532235719623110616717149
2081543131803954227244182
158168791161623191244863
142461981792511942025328238
62162781481281842169514434
2094323612924116686135247133
EDU>>B=[0:2:100linspace(101,199,25680)200:2:256];size(B)
%Createnewgrayscalemapping
ans=%thatcompressestheendsand
%expandsthemiddleofthe
1256%spectrum;mustbe256entries!
EDU>>floor(B(A+1))%RemapAbychoosingentriesof
%thenewmap(B)accodingtovalues
ans=%inA.Notetheadditionof1,to
%shift[0255]to[1256].
4109148168341901791379010
1121791603496210166210143195
188165169341255419710413110
2461021684111187110194165145
615719610318120613116516796
188158414511676102199232173
160165116136162601614194107
151901821722461803825054220
10616211515414317419212515266
18884216144226164120147238146
Thisefficient,butlesstransparent,implementationofaremappingcouldalsobedoneviaforloops(oneortwo,
dependingonimplementation),butthatwouldbemuch,muchslowerforlargematrices.
LoadingandSavingData
ThekeytoloadingdataintoMatlabistorememberthatMatlabonlyusesmatrices.Thatmeansthatifyouwant
toeasilyreadadatasetintoMatlab,alloftherowsmusthavethesamenumberofelements,andtheymustall
benumbers.
Mostcommonly,you'llbedealingwithatext(ASCII)file.Ifyouhaveasetofdataondiskinafilecalled
points.dat,thentoloadit,youwouldtype:
>>loadpoints.dat
ThiswillloadyourdataintotheMatlabvariablepoints.Let'sassumethatthefilepoints.datcontainstwo
columns,wherecolumn1isheightandcolumn2isdistance.Tobreakapartpointsintosomethingmore
meaningful,weuse:
>>height=points(:,1);
>>distance=points(:,2);
Thiscreatesavectorheightfromthefirstcolumn(allrows),anddistancefromthesecondcolumn.
TosavethesamedataintoanASCIIfilecalledmydata.dat,weuseeither:
>>savemydata.datheightdistanceascii %commonformfor
%commandline
or
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 8/16
13/02/2017 Geology&GeophysicsMatlabTutorial
>>save('mydata.dat','height','distance','ascii');
%commonformfor
%useinscriptsand
%functions
TheasciiflagisimportanthereittellsMatlabtomakethefileinASCIItext,notaplatformindependant
binaryfile.Withouttheflag,thefilewouldbeunreadablewithstandardeditors.Textisthemostportableand
editableformat,butislargerondisk.Matlab'sbinaryformatiscompatibleacrossallplatformsofMatlab
(Windows,UNIX,Mac,etc.),andismorecompactthantext,butcannotbeeditedoutsideofMatlab.
YouwillnotethatwhenMatlabsavesfilesinASCIIformat,itusesscientificnotationwhetheritneedsitornot.
MorepowerfulandflexiblesaveandloadschemesexistinMatlabtheyusethefprintf()andfscanf()functions
alongwithfopen()tocontrolfileoutput.Adiscussionoftheintricaciesofusingfscanf/fprintfisbeyondthis
tutorialseethehelppagesorsomeonewithfirsthandexperience.
Plotting
Nowthatwecansave,load,andcreatedata,weneedawaytoplotit.Themainfunctionformaking2
dimensionalplotsiscalledplot.Tocreateaplotoftwovectorsxandy,typeplot(x,y).Withonlyoneargument
(plot(x))plotwillplottheargumentxasafunctionofitsindex.Ifxisamatrix,plotwillproduceaplotofthe
columnsofxeachinadifferentcolororlinestyle.Moredetailonthebasicuseofplotisavailableviathehelp
plotcommandinMatlab.
Thatbringsustothethirdpossibleargumentforplot,thelinestyle.plot(x,y,s)willplotyasafunctionofx
usinglinestyles,wheresisa1to3characterstring(enclosedbysinglequotes)madeupofthefollowing
characters.
yyellow .point
mmagenta ocircle
ccyan xxmark
rred +plus
ggreen solid
bblue *star
wwhite :dotted
kblack .dashdot
dashed
Forexample,tocreateaplotofxversusy,usingmagentacircles,typethecommandplot(x,y,'mo');.Toplot
morethanoneline,youcancombineplotsbytypingplot(x1,y1,s1,x2,y2,s2,...);.
Asanexample,plotarandomvector(10x1)andanintegervectorfrom1to10usingtwodifferentlinetypes:
>>y1=rand(10,1);
>>y2=linspace(1,0,10);
>>x=1:10;
>>plot(x,y1,'g+',x,y2,'r');
>>title('Testoflinetypestrings');
>>xlabel('XAxis');
>>ylabel('YAxis');
Theplotshouldlooksomethinglikethis:
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 9/16
13/02/2017 Geology&GeophysicsMatlabTutorial
Anotherusefulplottingcommandiscallederrorbar.Thefollowingexamplewillgenerateaplotoftherandom
vectory1usinganerrorof0.1aboveandbelowtheline:
>>errorbar(x,y1,ones(size(y1)).*0.1,'r')
>>title('Testoferrorbar');
>>xlabel('XAxis');ylabel('YAxis');
Theplotshouldnowlooksomethinglikethis:
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 10/16
13/02/2017 Geology&GeophysicsMatlabTutorial
LabellingthePlot
title,xlabel,andylabelcreatelabelsforthetopandsidesoftheplot.Theyeachtakeastringvariable,which
mustbeinsinglequotes.Oneotherlabellingfunctionthatmightbeusefulisthetextfunction.Thecommand
text(1,10,'Hereissometext');willwritethetextstring'Hereissometext'atthe(x,y)position(1,10)in
dataunits.
ChangingtheAxes
Onethingyoumightwanttodowithyourplotistochangetheaxes.Normally,Matlabautomaticallychooses
appropriateaxesforyou,butthey'reeasytochange.Theaxiscommandwillallowyoutofindoutthecurrent
axesandchangethem.
>>axis %Getthecurrentaxis
%settings
ans=
012.00000.20001.4000
>>axis([2100.21.0]) %Resetaxesextentsto
%[xminxmaxyminymax]
Sometimesyouwillwanttoswitchthepositionoftheplotorigin(normallyusedforplottingimagesof
matrices).Typing
>>axis('ij')
willswitchtheYaxisdirectionsothat(0,0)istotheupperright.
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 11/16
13/02/2017 Geology&GeophysicsMatlabTutorial
AppendingDatatoPlots
Sometimesit'susefultobeabletoaddsomethingtoaplotwindowwithouthavingtodrawtwolineswiththe
sameplotstatement(aswedidabove).SoMatlabhasacommand,holdwhichwillcausetheplottoremain(it
doesn'tredrawit).Typingholdonwillholdthecurrentplot,andholdoffwillreleasetheplot.Also,holdby
itselfwilltoggletheholdstate.Youmightalsowanttouseclftoclearthegraphicswindowandreleasethe
window.
UsingGraphicsHandlesinMatlab
ForthoseofyouthatwilluseMatlabtomakeplotsforpublicationsandpresentationswillgreatlybenefitfroma
fewusefulbutpoorlydocumentedMatlabfunctions.Thecommandsgetandsetallowtheusertocheckor
tweakaplotintomorepleasingform.Forexamplebyusingthesecommands,onecanchangefontsizes,colors,
linewidthsandaxeslabelsaswellasmanyotherplotattributes.
Wewillstartbygeneratingasimpleplot:
>>x=[0:100]*pi/50;
>>y=sin(x);
Alltheattributesofaplotarestoredinadatastructurewhichmaybeobtainedbytyping:
>>p=plot(x,y)
Bygivingaplotanoutputvarible,youhaveobtainedtheobjecthandles.Inordertofindoutwhathandlesexist
weusethegetcommand.
>>get(p)
Alistwillbeprintedoutwhichispartiallylistedbelow:
Color=[001]
EraseMode=normal
LineStyle=
LineWidth=[0.5]
...
Ifyouwishtoobtainthevaluetojustoneaxishandle,forexamplethelinestyle,thiscanbedonebytyping:
>>get(p,'LineStyle')
ans=
Eachoftheseisagraphichandlesthatmaybechangedbyusingthecommandset.Forexample,supposethat
wenowwishtomaketheplotredinsteadofblueandincreasethelinewidthfrom0.5to1.
>>set(p,'Color',[100],'LineWidth',1);
Anygraphichandlemaybechangedusingthismethod.AsyoubegintouseMatlab,thesecommandsmaynot
beusedoften,butasyoubecomemoreproficient,youmayfindthesecommandstobeinvaluable.Other
attributesofaplotcanbechangedbyusinggca(foraxesproperties)andgcf(forfigurewindowproperties).
Typeget(gca)andget(gcf)toseewhatotherattributesmaybechanged.AndlikeanyotherpartofMatlab,
thesecommandsmaybeaddedtoscriptstocreatedcustomplots.
Creatingmfiles
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 12/16
13/02/2017 Geology&GeophysicsMatlabTutorial
InMatlab,youcancreateafileusingMatlabcommands,calledanmfile.Thefileneedstohavea.mextension
(hencethenamemfile).Therearetwotypesofmfiles:(1)scriptsand(2)functions.Wewillstartwith
scripts,astheyareeasiertowrite.
MatlabScripts
RunningaMatlabscriptisthesameastypingthecommandsintheworkspace.Anyvariablescreatedorchanged
inthescriptarechangedintheworkspace.Ascriptfileisexecutedbytypingthenameofthescript(withoutthe
.mextension).Scriptfilesdonottakeorreturnanyarguments,theyonlyoperateonthevariablesinthe
workspace.Ifyouneedtobeabletospecifyanargument,thenyouneedtouseafunction.Hereisanexampleof
asimplescripttoplotafunction:
%makefunction.m
%scripttoploterfcindomain[0,pi]
x=linspace(0,pi,25); %Createxfrom0topiwith25values
y=erfc(x); %Calc.erfcofx
scl=0.25; %Plottingscalingfactor
y=y*scl;
plot(x,y,'r'); %Plotxandy
title('MyScript'); %Createatitle
xlabel('X'); %Labelthexandyaxes
ylabel('Y');
Notetheuseof'%'characterstointroducecomments,justasintheexamplesthroughoutthistutorial.Ingeneral,
Matlabtreatsanythingaftera'%'asifitwasn'ttherecommentsaresilentlyignored.Thiscanbeveryuseful
whenwritingmfiles,asdebuggingcommandscanbecommentedoutafterthemfileistested.
Runningthismfileproducesthefollowingvariablesintheworkspaceandplot(inaseparatewindow):
>>whos %Emptyworkspace;novariablesdefined
>>makefunction %Createvars,plot
>>whos %Listvarsinworkspace
NameSizeBytesClass
scl1x18doublearray
x1x25200doublearray
y1x25200doublearray
Grandtotalis51elementsusing408bytes
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 13/16
13/02/2017 Geology&GeophysicsMatlabTutorial
Youshouldnoticethatallofthevariablesusedinthescriptarenowsittingintheworkspace,sothattheycanbe
usedagain.Thisisexactlythesameasiftheyhadbeentypedinseparately.Anytimeacomputationisgoingto
takemorethanasingleline,itisworthwhiletocreateathrowawaymfilethefilecanbesaved,edited,and
revisedmucheasierthanusingjustthecommandline.
MatlabFunctions
Matlabfunctionsareverysimilartoscripts,buttheycanacceptandreturnvaluesasarguments.Mostofthe
commandsavailableinMatlabareactuallyprewrittenMatlabfunctionsonlyasmallnumberofimportant
functionsarecompiledintotheprogram(e.g.matrixmultiply).
Towriteafunction,createanmfilewithafunctiondeclarationasthefirstline(seetheexample,below).The
returnvaluesinthedeclarationwillneedtobesetsomewhereinthefunctionbodywhatevervaluethese
variableshaveattheendofthefunctionwillbereturned.
Commentsimmediatelyafterthefunctiondeclarationwillbeusedasthehelppageforthefunctionitshould
haveusefulinformationonfunctionargumentsandreturnvalues.Ifthefunctionusesaspecial(named)
algorithm,thatisusefultoputinthehelpaswell.
Functionskeepvariableslocalvariablesdefinedinthefunctionarenotpartoftheworkspace,andthefunction
cannotaccessvariablesintheworkspaceunlesstheyarepassedasarguments.Hence,functionscandefinea
variablewithoutworryingifitalreadyexists.Allvariablesinafunctionarelostoncethefunctioncompletes.
Anexamplefunctiondefinition(fromafilenamedllsqErr.m):
function[mean,sigma]=llsqErr(x,y,N,dx,dy);
%function[mean,sigma]=llsqErr(x,y,N,dx,dy);
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 14/16
13/02/2017 Geology&GeophysicsMatlabTutorial
%
%Generatemeanands.d.ofslopeandintercept
%forlinearleastsquaresfittox,ydataset,usingMC
%techniquewithrandomerrorsofscaledx,dy.Randomerrors
%areuniformlydistributed,andsymmetric(withscaledx,dy)
%aboutxandyvalues.
%
%x,yarevectorsofdata,oflength>2
%dx,dyarescalars
%Nisscalar(#oftrials);typicallyshouldbe>1e3
%
%UsesNtrialswithrandomperturbationscomputedforeachtrial
%
%Returnsvaluesas[slopeintercept]formeansands.d.s
%%Notes%%
%Thiscodereallyoughttoguaranteethattherandomlygenerated
%pertrubationsareunique.Thisisassumedfromtheuseofa
%pseudorandomnumbergenerator,andthelikelyeventthatNis
%lessthantherecurrenceintervalofthePRNG.
%
%Itappearsnecessarytocomputethepredictederrorsforeach
%datasetindividually;attemptstogenerateageneralcorrelation
%plotdidn'tpanout.
m=zeros(N,2);
fori=1:N
xh=x+dx*(2*rand(size(x))1);%generateperturbedx,yvecs
yh=y+dy*(2*rand(size(y))1);
p=polyfit(xh,yh,1);%getslope,intercept
m(i,:)=p;%store
end
mean=[mean(m(:,1))mean(m(:,2))];
sigma=[std(m(:,1))std(m(:,2))];
Thisfunctionaccepts5arguments:x,y,N,dx,anddy.Itreturnstwovectors:meanandsigma.Notethatthe
commentsafterthefunctiondeclarationindicatewhattheargumentsandreturnvaluesare,aswellashowthe
functiondoesits'work.Alsonotethattherearecommentsaboutpossibleproblemswiththisalgorithmand
implementation.Auserlookingatthesourcecodeforthisfunctioncandeterminewhatishappening,andwhat
mightneedtobechanged.Alsonotethatthefunctionusessimplevariablenames,whichcouldexistinthe
workspace(x,y,etc.)becausethisisafunction,thevariablesusedarenotpartoftheworkspace,sothereareno
concerns.
Whenausergetshelpforthisfunction,thefirstsetofcomments(uptotheblankline)isreturnedasthehelp
page:
>>helpllsqErr
function[mean,sigma]=llsqErr(x,y,N,dx,dy);
Generatemeanands.d.ofslopeandintercept
forlinearleastsquaresfittox,ydataset,usingMC
techniquewithrandomerrorsofscaledx,dy.Randomerrors
areuniformlydistributed,andsymmetric(withscaledx,dy)
aboutxandyvalues.
x,yarevectorsofdata,oflength>2
dx,dyarescalars
Nisscalar(#oftrials);typicallyshouldbe>1e3
UsesNtrialswithrandomperturbationscomputedforeachtrial
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 15/16
13/02/2017 Geology&GeophysicsMatlabTutorial
Returnsvaluesas[slopeintercept]formeansands.d.s
SavingYourSession
Oneotherusefulcommandisthediarycommand.Typing
>>diaryfilename.txt
willcreateafilewithallthecommandsyou'vetyped.Whenyou'redone,typing
>>diaryoff
willclosethefile.Thismightbeusefultocreatearecordofyourworktohandinwithalabortocreatethe
beginningsofanmfile.
EndoftheTutorial
Atthispoint,youshouldknowenoughtomaneuveraroundinMatlabandfindwhateverelseyouneed.Helpis
availablefromthebuiltinhelpcommand,theonlinehelpsystematwww.mathworks.com,orfellowstudents
andfaculty.
Questions?Comments?Suggestions?
Contactgettings@mines.utah.edu
http://thermal.gg.utah.edu/tutorials/matlab/matlab_tutorial.html 16/16