Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Loading Data Into MATLAB PDF

MATLAB is very useful for plotting data from other sources, e.g., experimental measurements. MATLAB can easily handle tab or spacedelimited text files. The load command requires that your data file contain no text headings or column labels. To get around this restriction you must use more advanced file I / O commands.

Uploaded by

Ashish Agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Loading Data Into MATLAB PDF

MATLAB is very useful for plotting data from other sources, e.g., experimental measurements. MATLAB can easily handle tab or spacedelimited text files. The load command requires that your data file contain no text headings or column labels. To get around this restriction you must use more advanced file I / O commands.

Uploaded by

Ashish Agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

05/08/2015

LoadingDataintoMATLAB

LoadingDataintoMATLABforPlotting
Inadditiontoplottingvaluescreatedwithitsowncommands,MATLABisveryusefulforplotting
datafromothersources,e.g.,experimentalmeasurements.Typicallythisdataisavailableasaplain
textfileorganizedintocolumns.MATLABcaneasilyhandletaborspacedelimitedtext,butitcannot
directlyimportfilesstoredinthenative(binary)formatofotherapplicationssuchasspreadsheets.
ThesimplestwaytoimportyourdataintoMATLABiswiththeloadcommand.Unfortunately,the
loadcommandrequiresthatyourdatafilecontainnotextheadingsorcolumnlabels.Togetaround
thisrestrictionyoumustusemoreadvancedfileI/Ocommands.BelowIdemonstratebothapproaches
withexamples.I'veincludedanmfiletohandlethemorecomplexcaseofafilewithanarbitrary
numberoflinesoftextheader,inadditiontotextlabelsforeachcolumnofdata.Thoughhardlya
cureall,thisfunctionismuchmoreflexiblethantheloadcommandbecauseitallowsyoutoprovide
documentationinsideyourdatafile.
Here'sanoutlineofthissection
TheMATLABloadCommand
Asimpleplotofdatafromafile
Plottingdatafromfileswithcolumnheadings

TheMATLABloadCommand
ThereismorethanonewaytoreaddataintoMATLABfromafile.Thesimplest,thoughleast
flexible,procedureistousetheloadcommandtoreadtheentirecontentsofthefileinasinglestep.
Theloadcommandrequiresthatthedatainthefilebeorganizedintoarectangulararray.Nocolumn
titlesarepermitted.Oneusefulformoftheloadcommandis
loadname.ext

where``name.ext''isthenameofthefilecontainingthedata.Theresultofthisoperationisthatthe
datain``name.ext''isstoredintheMATLABmatrixvariablecalledname.The``ext''stringisany
threecharacterextension,typically``dat''.Anyextensionexcept``mat''indicatestoMATLABthatthe
dataisstoredasplainASCIItext.A``mat''extensionisreservedforMATLABmatrixfiles(see
``helpload''formoreinformation).
SupposeyouhadasimpleASCIIfilenamedmy_xy.datthatcontainedtwocolumnsofnumbers.The
followingMATLABstatementswillloadthisdataintothematrix``my_xy'',andthencopyitintotwo
vectors,xandy.

>>loadmy_xy.dat;%readdataintothemy_xymatrix
>>x=my_xy(:,1);%copyfirstcolumnofmy_xyintox

http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html

1/5

05/08/2015

LoadingDataintoMATLAB

>>y=my_xy(:,2);%andsecondcolumnintoy

Youdon'tneedtocopythedataintoxandy,ofcourse.Wheneverthe``x''dataisneededyoucould
refertoitasmy_xy(:,1).Copyingthedatainto``x''and``y''makesthecodeeasiertoread,andis
moreaestheticallyappealing.TheduplicationofthedatawillnottaxMATLAB'smemoryformost
modestdatasets.
Theloadcommandisdemonstratedinthefollowingexample.
IfthedatayouwishtoloadintoMATLABhasheadinginformation,e.g.,textlabelsforthecolumns,
youhavethefollowingoptionstodealwiththeheadingtext.
Deletetheheadinginformationwithatexteditorandusetheloadcommand:(
Usethefgetlcommandtoreadtheheadinginformationonelineatattime.Youcanthenparse
thecolumnlabelswiththestrtokcommand.ThistechniquerequiresMATLABversion4.2cor
later.
Usethefscanfcommandtoreadtheheadinginformation.
Oftheseoptions,usingfgetlandstrtokisprobablythemostrobustandconvenient.Ifyoureadthe
headingtextintoMATLAB,i.e.,ifyoudon'tusetheloadcommand,thenyouwillhavetoalsoread
theplotdatawithfscanf.Theexample,Plottingdatafromfileswithcolumnheadingsshowshowthis
isdone.

Asimpleplotofdatafromafile
Thisexampleshowyouhowtoloadasimpledatasetandplotit.
ThePDXprecip.datfilecontainstwocolumnsofnumbers.Thefirstisthenumberofthemonth,and
thesecondisthemeanprecipitationrecordedatthePortlandInternationalAirportbetween1961and
1990.(ForanabundanceofweatherdatalikethischeckouttheOregonClimateService)
HerearetheMATLABcommandstocreateasymbolplotwiththedatafromPDXprecip.dat.These
commandsarealsointhescriptfileprecipPlot.mforyoutodownload.

>>loadPDXprecip.dat;%readdataintoPDXprecipmatrix
>>month=PDXprecip(:,1);%copyfirstcolumnofPDXprecipintomonth
>>precip=PDXprecip(:,2);%andsecondcolumnintoprecip

>>plot(month,precip,'o');%plotprecipvs.monthwithcircles

>>xlabel('monthoftheyear');%addaxislabelsandplottitle
>>ylabel('meanprecipitation(inches)');
>>title('MeanmonthlyprecipitationatPortlandInternationalAirport');

Althoughthedatainthemonthvectoristrivial,itisusedhereanywayforthepurposeofexposition.
Theprecedingstatmentscreatethefollowingplot.

http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html

2/5

05/08/2015

LoadingDataintoMATLAB

Plottingdatafromfileswithcolumnheadings
Ifallyourdataisstoredinfilesthatcontainnotextlabels,theloadcommandisallyouneed.Ilike
labels,however,becausetheyallowmetodocumentandforgetaboutthecontentsofafile.Tousethe
loadforsuchafileIwouldhavetodeletethecarefullywrittencommentseverytimeIwantedtomake
aplot.Then,inordertominimizemyeffort,Imightstopaddingthecommentstothedatafileinthe
firstplace.Foruscontrolfreaks,thatleadstoanunacceptableincreaseinentropyoftheuniverse!The
solutionistofindawaytohaveMATLABreadanddealwiththetextcommentsatthetopofthefile.
ThefollowingexamplepresentsaMATLABfunctionthatcanreadcolumnsofdatafromafilewhen
thefilehasanarbitrarylengthtextheaderandtextheadingsforeachcolumns.
ThedatainthefilePDXtemperature.datisreproducedbelow

Monthlyaveragedtemperature(19611990)PortlandInternationalAirport
Source:Dr.GeorgeTaylor,
OregonClimateService,http://www.ocs.oregonstate.edu/
TemperaturesareindegreesFarenheit
MonthHighLowAverage
1
45.36 33.84 39.6
2
50.87 35.98 43.43
3
56.05 38.55 47.3
4
60.49 41.36 50.92
5
67.17 46.92 57.05
6
73.82 52.8
63.31
7
79.72 56.43 68.07
8
80.14 56.79 68.47
9
74.54 51.83 63.18
10
64.08 44.95 54.52
11
52.66 39.54 46.1
12
45.59 34.75 40.17

Thefilehasafivelineheader(includingblanklines)andeachcolumnofnumbershasatextlabel.To
usethisdatawiththeloadcommandyouwouldhavetodeletethetextlabelsandsavethefile.A
bettersolutionistohaveMATLABreadthefilewithoutdestroyingthelabels.Betteryet,weshould
http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html

3/5

05/08/2015

LoadingDataintoMATLAB

beabletotellMATLABtoreadandusethecolumnheadingswhenitcreatestheplotlegend.
ThereisnobuiltinMATLABcommandtoreadthisdata,sowehavetowriteanmfiletodothejob.
OnesolutionisthefilereadColData.m.Thefulltextofthatfunctionwon'tbereproducedhere.You
canclickonthelinktoexaminethecodeandsaveitonyourcomputerifyoulike.
HereistheprologuetoreadColData.m

function[labels,x,y]=readColData(fname,ncols,nhead,nlrows)
%readColDatareadsdatafromafilecontainingdataincolumns
%thathavetexttitles,andpossiblyotherheadertext
%
%Synopsis:
%[labels,x,y]=readColData(fname)
%[labels,x,y]=readColData(fname,ncols)
%[labels,x,y]=readColData(fname,ncols,nhead)
%[labels,x,y]=readColData(fname,ncols,nhead,nlrows)
%
%Input:
%fname=nameofthefilecontainingthedata(required)
%ncols=numberofcolumnsinthedatafile.Default=2.Avalue
%ofncolsisrequiredonlyifnlrowsisalsospecified.
%nhead=numberoflinesofheaderinformationattheverytopof
%thefile.Headertextisreadanddiscarded.Default=0.
%Avalueofnheadisrequiredonlyifnlrowsisalsospecified.
%nlrows=numberofrowsoflabels.Default=1
%
%Output:
%labels=matrixoflabels.Eachrowoflablesisadifferent
%labelfromthecolumnsofdata.Thenumberofcolumns
%inthelabelsmatrixequalsthelengthofthelongest
%columnheadinginthedatafile.Morethanonerowof
%labelsisallowed.Inthiscasethesecondrowofcolumn
%headingsbeginsinrowncol+1oflabels.Thethirdrow
%columnheadingsbeginsinrow2*ncol+1oflabels,etc.
%
%NOTE:Individualcolumnheadingsmustnotcontainblanks
%
%x=columnvectorofxvalues
%y=matrixofyvalues.yhaslength(x)rowsandncolscolumns

Thefirstlineofthefileisthefunctiondefinition.Followingthatareseverallinesofcomment
statementsthatformaprologuetothefunction.Becausethefirstlineafterthefunctiondefinitionhas
anonblankcommentstatement,typing``helpreadColData''attheMATLABpromptwillcause
MATLABtoprinttheprologueinthecommandwindow.Thisishowtheonlinehelptoall
MATLABfunctionsisprovided.
Theprologueisorganizedintofoursections.Firstisabriefstatementofwhatthefunctiondoes.Next
isasynopsisofthewaysinwhichthefunctioncanbecalled.Followingthattheinputandoutput
parametersaredescribed.
HerearetheMATLABcommandsthatusereadColData.mtoplotthedatainPDXtemperature.dat.
ThecommandsarealsointhescriptfilemulticolPlot.m

>>%readlabelsandxydata
>>[labels,month,t]=readColData('PDXtemperature.dat',4,5);

>>plot(month,t(:,1),'ro',month,t(:,2),'c+',month,t(:,3),'g');

>>xlabel(labels(1,:));%addaxislabelsandplottitle
>>ylabel('temperature(degreesF)');

http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html

4/5

05/08/2015

LoadingDataintoMATLAB

>>title('MonthlyaveragetemperatureforPortlandInternationalAirport');

>>%addaplotlegendusinglabelsreadfromthefile
>>legend(labels(2,:),labels(3,:),labels(4,:));

Thesestatmentscreatethefollowingplot.

[PrecedingSection][MasterOutline][SectionOutline][NextSection]

http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlotData.html

5/5

You might also like