COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture...
Transcript of COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture...
COMS3101ProgrammingLanguages:MATLAB
Lecture3
Fall2013Instructor:IliaVovsha
hBp://www.cs.columbia.edu/~vovsha/coms3101/matlab
LectureOutline
Loadingandsavingdata Moreinput/output BasicploJng,figures Datastructures:cellarrays,structs,strings,handles Nextlecture:formulaRngandsolvingproblems Nextlecture:advancedfuncRonality,opRmizaRon
3.2
UsefulCommands
Blockcomments%{…%} cumsum(),cumprod()
mod(),rem() isempty(),isvector()
ForcomplicatedfuncRonsreadingthe‘help’documentaRonisnotsufficient(moredetailsinthehelpbrowser‘doc’)
3.3
HW#1
SoluRonsareposted(average:) Part2willbediscussednextweek
FuncRons–SubfuncRons
TypicallyonefuncRonforonefile(filename=funcRonname)
AlsopossibletoincludemulRplefuncRonsinonefile:• MainfuncRonandsub‐funcRons• Sub‐funcRonsareonly“visible”tootherfuncRonsinthe
samefile• Usefulwhenyouhavemanyminorandveryspecific
rouRnes
• Type‘helpfuncRon’toseeanexample
3.5
Exercise(InClass)
FuncRons&matrixmanipulaRon
SupposeMisa{0,1}matrixthatrepresentsadirectedgraph.IfM(i,j)=1,thenthereexistsadirectededgefromitoj.WriteafuncRonthattakesMasinput,and(foreveryedge)printstheword‘edge’followedbytheverRcesoftheedge.ThefuncRonshouldreturnthetotalnumberofedgesinthegraphinthevariableT
3.6
Input/Output–sprinl()
sprinl()converts(formats)dataintoastring:• Example:S=sprinl(‘myfile%d’,2);• Thecharacterfollowing%specifiestheformatintowhichthesupplied
parameterisconverted
• CanspecifydifferentformatsandsupplymulRpleparameters
• Example:S=sprinl(‘myfile%d%s’,2,‘test’);
Commonformats:%d(integer)%s(string)%g(float) Example:1.prefix=‘home_dir/mydata’;
2.file_num=2;
3.filename=sprinl(‘%s%d.txt’,prefix,file_num);
3.7
I/O–Formats
format<type>:• Controlsoutputformats,andhasnoeffecton
computaRon
• ForbeBerappearanceofnumberswithmanydecimaldigitsuse‘formatshortg’
• Toremoveannoyingspaces(line‐feeds)use‘formatcompact’
• PossibletospecifymulRpleformatsaslongastheydon’tcontradicteachother
3.8
I/O–UserInput
input()isacommandthatpromptstheusertoentersomeinput
Torecordtheinput,youneedtosupplyavariable Theinputstreamisclosedwhentheuserhitsenter Bydefault,theexpectedinputisaMATLABexpression
Examples:• color=input(‘Enteryourchoice’);
• color=input(‘Enteryourchoice’,‘s’);
• color=input(‘Enteryourchoice\n’,‘s’);
3.9
I/O–MATLABData
MATLABhasitsownfileextension“.mat”
A.matfileisstoredinbinaryformat(unlikesaytextfilesitispointlesstoviewa.matfile)
Storingdataina.matfileisconvenient:• Canloadandsavedatausingbuilt‐incommands
• Canload/savespecificvariablesto/fromtheworkspace Examples(load):
• loadfile1; %AutomaRcallychecksforfile1.matandloadsallvars
• v1=load(‘file1.mat’,X);%LoadsthevariableXfromfile1.mat
3.10
I/O–MATLABData
Examples(save):• savefile1.matX; %SavevariableXtofile1.mat• save(filename,‘X’);%SaveXtoafilewhosenameis
storedinthevariable‘filename’
• savefile1.matXYZ;%SaveX,Y,Ztofile1.mat
3.11
I/O–TextFiles
Commands:fopen(),fclose(),fgetl(),fseek(),fprinl()
Morecomplexthanloading.matfiles.Firstneedtoopenafilefopen(),thenread/writethedatafgetl(),fprinl(),thenclosethefilefclose()
Toopenafile,wecreatea‘fileidenRfier’:• FID=fopen(‘myfile.text,‘r’);%2ndargumentspecifiesoperaRon
• ‘r’(read),‘w’(write),‘a’(append)
• Incaseoffailure,FID=‐1
• Alwayscheckwhetherfilewasopened
3.12
I/O–TextFiles
Tocloseafileiseasy:• FID=fopen(‘myfile.text,‘r’);• SOPEN=fclose(fid); %returns‐1iffailedtoclose
Readalinefromafile:• myline=fgetl(FID);%Readasingleline
Rewindfile:• fseek(fid,0,‐1);%O{ennecessarytotraverseafilemulRpleRmes
Writetoafile:• fprinl()writesformaBeddatatofile
• fprinl(fid,FORMAT,ARRAY); %Formatisastring
3.13
I/O–TextFiles
Typicallyfileshaveaspecificformat:numericdataseparatedbysomedelimiter(acharacter)
MATLABhasbuilt‐infuncRons:dlmread(),dlmwrite()
Examples: M=dlmread(‘file1.txt’,‘\t’) %ReadtabdelimiteddataintoM
Chooseanycharacter(s)asyourdelimiter.Bewaryofspacesordotsasdelimiters
M=dlmread(‘file1.txt’,‘;’,[R1C1R2C2])%3rdparameteristherange(zero‐based)fromwhichthedataisread
dlmwrite(‘file1.txt',M,’\t’) %WriteMtoatab‐delimitedfile
3.14
I/O–Images
Imagearejustmatrices.ColorimageshaveanaddiRonaldimension(B,G,Rvalues).Grayscaleimagesjusthavepixelvalues
Built‐incommands:imread(),imwrite() Examples:
• M=imread(‘myphoto.jpg’); %Readanimage
• imwrite(M,‘myphoto,jpg’); %Inferstheformatfromtheext.
• imwrite(M,‘myphoto’,‘JPEG’);
3.15
Exercise(InClass)
Loadingandsavingasequenceoffiles. Supposeyouhaveadirectory‘home/mydata’whichcontains100filesallnamed‘dataset_#.mat’.EachfilesstoresamatrixM.WriteafuncRonthattakesaninputparameterN,andopenseachfile(from1toN),sortsthematrixMinroworder,andsavethesortedmatrixtoanewfilenamed‘newdata_#.mat’
3.16
BasicPloJng
ThegeneralfuncRonwewilluseisplot()• ThefuncRonautomaRcallygeneratesafigureforyou
TherearemanyopRonsavailable:• CanspecifytheproperResoftheplotindetail• CanhavemulRplecurvesonthesameplot
• CanhavemulRpleplotsinonefigure• MoreinteresRngplotsarepossiblewithbar(),pie()
3.17
BasicPloJng–OpRons
OpRon1:plot(X,Y)• AssumingX&Yarevectors,plotsYvs.X• AsolidcurveconnecRngthepoints• Y&Xmusthavethesamelength
OpRon2:plot(Y)• SimilartoopRon1,butplotsYvs.‘index’
OpRon3:plot(X,Y,S)• ‘S’isanopRonalparameter
• Acharacterstringthatcontrolsplotappearance
3.18
BasicPloJng–OpRons
OpRon3:plot(X,Y,S)• Example:S=‘rs:’plotsared,doBed,linewithasquare
ateachdatapointonthecurve
• ‘helpplot’forallthestringopRons OpRon4:plot(X,Y,S,<param>,<val>)• AddiRonalplotproperRescanbespecifiedwithdifferent
parametersandvalues
• Example:plot(X,Y,S,‘LineWidth’,2)settheline‐widthtosize2
• Type‘docplot’foralistoftheseproperRes
3.19
BasicPloJng–OpRons
MoreopRons:• Cansetasmanyparametersasyouwish(justcallthe
funcRonwithmoreparameter‐valuepairs)
• Cancombineplots:plot(X1,Y1,X2,Y2)
• Can‘duplicate’aplot:plot(X,Y,S1,X,Y,S2)• PlotcombinaRonisfine,butnotthemostelegant
approach
3.20
BasicPloJng–Figures
Problem:• plot(x,y);plot(x,z);replaces1stplotwith2nd
SoluRon:‘figure’command• plot(x,y);figure;plot(x,z);
• figure(1);figurewithhandle#1
Closefigures:• Specificfigure:close1• Allfigures:closeall
MATLABstoresahandletoeachfigure
3.21
BasicPloJng–Figures
MulRpleplots:• plot(x,y);holdon;plot(x,z);holdoff;
MulRpleplots,samefigure:• subplot()command
• figure(1);subplot(2,2,1);
3.22
BasicPloJng–Appearance
ManyopRons,canmodifyplotsusingtheGUI
Commands:Rtle(),xlabel(),ylabel(),axis(),legend() Example:1.figure(1);
2.Rtle(‘test’);3.xlabel(‘quanRty’);ylabel(‘price’);
4.axis([15110]); %AXIS([XMINXMAXYMINYMAX])5.gridon; %Showgridlines
6.xlim([13]); %Changex‐axislimits
3.23
BasicPloJng–Figures
YouhavecreatedmulRplefigures.Whichoneisthe‘currentfigure’?
Answer:lastfigureyouclickedon BeBeranswer:usegcf()togetthehandle Usefigure(#)tomake‘#’thecurrenthandle Commands:gcf(),gca(),clf() Set‘object’properResusingtheset()command:
• set(gca,'XTick',[123]) %Toset‘Rcks’onthex‐axis
Get‘object’properResusingtheget()command
3.24
Saving&LoadingFigures
MATLABhasaspecialfigureformat:‘.fig’
Useopenfig(‘name.fig’)toopenasavedfigure Savingfigures:useprintcommand– GeneralForm
– print -dformat filename – Example – print –depsc ‘figure.eps’
‘eps’isaformatthatstoresyourimageinavectorizedway,whichavoidsqualitylossa{errescaling.It’sparRcularlyusefulwhenusedwithinLaTeX
3.25
Exercise(InClass)
Simpleplot
WriteafuncRonthathasoneinputparameterM,amatrixwith3columns.Columns{1,2}ofMarethe{x,y}coordinatesofpointsintheplane.Column3istheclasstowhichthepointbelongs.Thevaluesofcolumn3areoneoftwounknownintegers
YourfuncRonshouldplotallpoints,pointsinoneclassshouldbedotsinred,pointsinthe2ndclassshouldbesquaresingreen.Adjustyouraxesproperlysothatthefurthestpointsarenotontheedge
3.26
DataStructures–Structs
Whenacompositedatastructureisrequired,usea‘struct’(structurearray)• MulRplefields,differentdatastructuresforeachfield
• SimilarinformtoC++classes• Use‘dot’toaccessfields
IniRalizaRon:• S=struct([]) %Emptystruct,nofields
• S=struct(‘f1’,v1,‘f2’,v2) %Structwithtwofields• S.field1=2.5; %Createdirectly
3.27
DataStructures–Structs
FuncRonality:• isstruct(S); %CheckifSisastruct• S=selield(S,‘field1’,5); %Setafieldtoavalue
• isfield(S,‘field1’); %Checkiffieldexists
Example:
1.S=struct(‘vec’,[1,2,3],‘mat’,rand(3));2.my_field=‘mat’;3.isfield(S,my_field);
3.28
Structs–Note
WhenmulRplevariablesaresavedina.matfile,andthenloadedintoasinglevariable,theyaresavedasfieldsofastruct
Example:1.savefile1.matXYZ;2.S=load(‘file1’);
3.isstruct(S); %Structwith3fields:S.X,S.Y,S.Z
3.29
DataStructures–CellArrays
Cellarrayisan‘arrayofmatrices’.• Eachelementofacellarraycanbeascalar/vector/matrix.• Whyisituseful?Recallthe1stexercise(loadinga
sequenceoffiles)
IniRalizaRon:• C=cell(N) %NbyNarrayofemptymatrices• C=cell(N,M) %NbyMarrayofemptymatrices
• Usebrackets{}toaccesselements
• Rulesforregulararraysapply• C={[1][1,2,3];rand(3),rand(3)}; %Createdirectly
3.30
CelltoStructConversion
Commands:cell2struct(),struct2cell()• S=cell2struct(C,my_fields,my_dim)• ‘my_fields’isacellarrayofstrings
Example:1.my_fd={‘num’,‘name’,‘naRon’};2.my_arr={8,‘Iniesta’,‘Spain’};
3.my_st=cell2struct(my_arr,my_fd,2);%Youare‘folding’thedimension,sizemustmatch
3.31
Strings–FuncRons
MATLABisnotrecommendedasatoolformanipulaRngstrings.However,thefuncRonalityisavailable
Checkstring:• isleBer(str),isspace(str)
Convertstring:• lower(str),upper(str)• str2num(str),num2str(num)
3.32
Strings–FuncRons
OperaRonsonstrings:• strtok(str,delim),strcmp(str1,str2),strfind(str1,paBern)
Regularexpressions(helpregexp):conciseandflexiblemeansformatchingstrings
Example:1.str1=‘one!,notwo’;2.[bef_delim,a{_delim]=strtok(str1,‘!’);
3.idx=strfind(str1,‘n’);4.res1=strcmp(‘hi’,‘HI’);
5.res2=strcmp(‘hi’,lower(‘HI’);
3.33