5. matlab i/o 1 - Jeff Freymueller

advertisement
5.MATLABI/O1
BeyondtheMouse
GEOS436/636
JeffFreymueller,Oct4,2016
“TheUncomfortableTruthsWell”,
hMp://xkcd.com/568(April13,2009)
Topics
• 
• 
• 
• 
• 
• 
LoadingandSavingtheWorkspace
FileAccess
Plo$ngData
Annota,ngPlots
SavingaPlot
YouhaveseensomeoftheseinacZon
already,butwewillgointomoredetailthis
Zme.
LoadandSave
•  Youcansavesomeorallofyourworkspacetoa
file,andloaditbacklater
–  Thesefilescanbeasciitextorbinary
•  save filename
–  Savesallworkspacevariablestofilefilename.mat
•  save('filename', 'var1', 'var2');
–  Savesonlythevariablesvar1 andvar2 tofile
filename.mat
•  load filename
–  Loadsallthevariablessavedinfilefilename.mat
ReadingDatafromFiles
•  Firstbusiness:Openingandclosingfiles
•  Howtoreadandwritedatafrom:
–  MSExcelfiles
–  Textfiles
•  textread(deprecated)
•  textscan
•  fprina
OpeningandClosingFiles
•  FormostfuncZonsthatreaddatafromafile
orwritedatatoafile,youhavetoopenthe
filefirst,andcloseitwhenyouaredone.
•  MATLABcanhaveseveralfilesopenatonce,
andusesafileIDsothatyouaccessthe
correctfile.
•  YougetafileIDwhenyoucallthefuncZon
fopen(),andyoureleaseitwhenyoucall
fclose().
OpeningaFile:fopen()
•  fid=fopen(filename,mode)
–  Filenameisastringorstringvariablewiththe
nameofthefiletobeopened
–  ModeisastringorstringvariabletellingMATLAB
whethertoread,write,orappend:
•  ‘r’:read
•  ‘w’:write
•  ‘a’:append
Becarefulwith‘w’,asitwilloverwriteanexis6ngfile!
•  Don’tthrowawaythereturnvalue,asyouwill
needittoaccessthefile!
ClosingaFile:fclose()
•  fclose(fid)
–  fidisthefileIDofthefileyouwanttoclose.
•  Callfclose whenyouaredonewithafileso
thatyoucanbesureallchangesarewriMento
thefile(ifyouopenedforwriZng).
–  Whenyouwritetoafile,exactlywhenthatissavedto
diskdependsontheoperaZngsystem,notMATLAB
•  ItisgoodpracZcetoclosefileswhenyouare
done,likebrushingyourteethagereaZng.
–  Also,thereissomelimittohowmanyfilesMATLAB
cankeepopenatoneZme(itislarge,but…)
Reading/WriZngMSExcelFiles
•  TherearemanydatafileshangingaroundinMSExcel
format.Youmightwanttoreadone,orexportsome
dataintothatformat
•  Readwithxlsread,writewithxlswrite
–  OnWindowssystemswithExcelinstalled,xlsreadreads
anyfileformatrecognizedbyyourversionofExcel,
includingXLS,XLSX,XLSB,XLSM,andHTML-basedformats.
–  IfyoursystemdoesnothaveExcelforWindows,xlsread
operatesin‘basic’mode
–  IfyoursystemdoesnothaveExcelforWindows,orifthe
COMserver(partofthetypicalinstallaZonofExcel)is
unavailable,xlswriteoperatesinalimitedmode
xlsread
•  [num, txt, raw] = xlsread('myfile.xls',
'sheet23', 'A3:B7');
–  Firstargumentisthefilename
–  Secondargument(ifgiven)isthesheetname(default
isthefirstsheetifthisargumentisomiMed)
–  Thirdargument(ifgiven)isarangespecifierfor
elementsofthesheet.
–  Outputvalues
•  num–amatrixthatcontainsallnumericdata
•  txt–acellarraythatcontainsalltextdata
•  raw–cellarraywithcolumnsxlsreadcouldnotinterpret
xlsread:BasicMode
•  BasicModeforxlsread
–  BasicmodebehaviorchangeswithMATLABversion
–  OnlyreadsXLSfilescompaZblewithExcel97-2003
sogware(R2012aandlateralsoreadXLSXandothers).
–  ImportstheenZreacZverangeoftheworksheet.
–  RequiresastringtospecifytheSHEET,andthenameis
casesensiZve.
–  ExcelandMATLABcanstoredatesasstrings(suchas
‘10/31/96’)orserialdatenumbers.Serialdatenumbersin
Exceluseadifferentreferencedatethandatenumbersin
MATLAB.In‘basic’mode,xlsreadimportsalldatesasExcel
datenumbers.
•  TranslaZon:youmayhavedateproblemsinbasicmode
•  Justbeawarethatifyouwanttouseanyotherfeature
ofxlsread,youwillbeZedtoWindows
xlswrite
•  [status, msg] = xlswrite('myfile.xls', M,
'sheet42');
–  aMemptstowritematrixMtosheet42of
myfile.xls
–  Youcanalsospecifytherangeofelementstouse
–  Outputs:
•  status–1onsuccess,0onerror
•  msg–errormessageobjectwithfieldsmessageand
idenZfier
csvread,csvwrite
•  Youcanreadandwritecsv(commaseparated
values)filesonanymachine
•  M = csvread('filename', R, C)
–  readsdatafromthecommaseparatedvalue
formaMedfilestarZngatrowRandcolumnC.
–  RandCareopZonal
•  RandCarecountedfromzerosothatR=0andC=0specifies
thefirstvalueinthefile.
•  csvwrite('filename', M, R, C)
–  writesmatrixMstarZngatoffsetrowR,andcolumnC
inthefile
–  RandCareopZonal
•  dlmread anddlmwritecanuseanycharacter
asdelimiterinsteadofacomma(e.g.,':').
Textread
•  TextreadisadeprecatedfuncZon,whichmeans
thatitwilleventuallydisappear.
–  Innewcode,usetextscaninstead.
•  [A, B, C, ...] = textread('filename',
'format', N);
–  readsdatafromfile'filename' tomulZple
outputsA,B,C,...usingspecifiedformatunZlenZrefile
isread,orNZmes.Eachcolumnoffileinonearray
•  TextscanissimilarbutrequiresafileIDinsteadof
afilename
–  Meaningyouhavetoopenthefileyourself
Textscan
•  Textscanisreallygreat!Itisdesignedtoreadfiles
wherethevaluesareincolumns,definedby
whitespace(spacesortabs)
–  Ifyouwanttoreadstringsthatcontainspaces,you
havetouseanotherfuncZon
•  C = textscan(fid, 'format', N);
–  readsdatafromfilefidtocellarrayCusingspecified
formatunZlenZrefileisread,orNZmes
•  EachcolumnofdataisstoredinonecellofC
•  resumefromwhereyoulegoffbycallingtextscanagain
later).
Textscan
•  Wehaveuseditbefore,toreadfilesthathada
fewcolumnsofnumbers.
•  ReadfourfloaZngpointnumbers:
–  C = textscan(fid, '%f%f%f%f');
•  Readastring,andintegerandthenfloaZngpoint
numbers:
–  C = textscan(fid, '%s%d%f%f%f%f');
•  Readfromastring
–  C = textscan('2 4 6 8', '%d%d%d%d');
•  Morecomplexformatstatementscanbeused
Moregeneral:fscanf
•  Youcanreadanygeneralformatusingfscanf,but
itdoesnothandlestringsasnicelyastextscan.
•  [A,COUNT] = fscanf(FID,FORMAT,SIZE)
–  readsdatafromthefilespecifiedbyfileidenZfierFID,
convertsitaccordingtothespecifiedFORMATstring,
andreturnsitinmatrixA.
–  Stringscomebackascharacterarrays(numericvalues
inthematrixA)
•  Youcanusedsscanftodothesamefromastring.
WhatareTheseFormatCodes?
•  TheformatstringsusethestyleoftheC
programminglanguage
•  Read/writeastring:%s
–  A7characterstring:%7s
•  Read/writeafloaZngpointnumber:%f
–  Use9digits,4agerthedecimal:%9.4f
•  Read/writeaninteger:%d
•  ThereareotheropZonsaswell:help fscanf
Lower-levelFileAccess
•  TLINE = fgets(FID)
–  Returnsonelineoffileasatextstring,including
theendoflinecharacter(s)
•  TLINE = fgetl(FID)
–  Returnsonelineoffileasatextstring,without
theendoflinecharacter(s)
•  Youcanthenusesscanf()toreadanypart
ofthelinethatyoumightwant
–  Syntaxforsscanf followsthatforfscanf.
ReadinanImagewithImportdata
•  Importdataallowsyoutoreadthedatafromatext
fileintoastructure:
• 
• 
• 
• 
filename = 'myfile01.txt';
delimiter = ' ';
headerlines = 1;
A = importdata(filename,delimiter,headerlines);
•  Theinputfilemightlooklikethis:
Day1
95.01
23.11
60.68
48.60
89.13
Day2
76.21
45.65
1.85
82.14
44.47
Day3
61.54
79.19
92.18
73.82
17.63
Day4
40.57
93.55
91.69
41.03
89.36
Day5
5.79
35.29
81.32
0.99
13.89
Day6
20.28
19.87
60.38
27.22
19.88
Day7
1.53
74.68
44.51
93.18
46.60
ReadinanImagewithImportdata
•  Importdataallowsyoutoreadthecolor
valuesfromaJPEGfileintoanarraysothat
youcandisplayit:
•  A = importdata('ngc6543a.jpg');
•  image(A)
Output:fprina
•  fprinaistheworkhorseofwriZngout
formaMedprintoutput
•  count = fprintf(fid, 'format', A, ...);
–  formatsdatainmatrixA(andanyaddiZonal
arguments)accordingtoformatstringandwrites
tothefileassociatedwithfid
–  count–numberofbyteswriMen
Anfprinaexample
“Feature”alert:EachrowofthematrixiswriMenasacolumnintheoutputfile.
Or:EachcolumnofthematrixiswriMenasarowintheoutputfile
PlotngData
•  Willbecoveredindetailinthenextlecture
andlab.
PlotngData
•  Willbecoveredindetailinthenextlecture
andlab.
Download