33
COMS 3101 Programming Languages: MATLAB Lecture 3 Fall 2013 Instructor: Ilia Vovsha hBp://www.cs.columbia.edu/~vovsha/coms3101/matlab

COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

COMS3101ProgrammingLanguages:MATLAB

Lecture3

Fall2013Instructor:IliaVovsha

hBp://www.cs.columbia.edu/~vovsha/coms3101/matlab

Page 2: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

LectureOutline

  Loadingandsavingdata  Moreinput/output  BasicploJng,figures  Datastructures:cellarrays,structs,strings,handles  Nextlecture:formulaRngandsolvingproblems  Nextlecture:advancedfuncRonality,opRmizaRon

3.2

Page 3: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

UsefulCommands

  Blockcomments%{…%}  cumsum(),cumprod()

  mod(),rem()  isempty(),isvector()

  ForcomplicatedfuncRonsreadingthe‘help’documentaRonisnotsufficient(moredetailsinthehelpbrowser‘doc’)

3.3

Page 4: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

HW#1

  SoluRonsareposted(average:)  Part2willbediscussednextweek

Page 5: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

FuncRons–SubfuncRons

  TypicallyonefuncRonforonefile(filename=funcRonname)

  AlsopossibletoincludemulRplefuncRonsinonefile:•  MainfuncRonandsub‐funcRons•  Sub‐funcRonsareonly“visible”tootherfuncRonsinthe

samefile•  Usefulwhenyouhavemanyminorandveryspecific

rouRnes

•  Type‘helpfuncRon’toseeanexample

3.5

Page 6: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

Exercise(InClass)

  FuncRons&matrixmanipulaRon

  SupposeMisa{0,1}matrixthatrepresentsadirectedgraph.IfM(i,j)=1,thenthereexistsadirectededgefromitoj.WriteafuncRonthattakesMasinput,and(foreveryedge)printstheword‘edge’followedbytheverRcesoftheedge.ThefuncRonshouldreturnthetotalnumberofedgesinthegraphinthevariableT

3.6

Page 7: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 8: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

I/O–Formats

  format<type>:•  Controlsoutputformats,andhasnoeffecton

computaRon

•  ForbeBerappearanceofnumberswithmanydecimaldigitsuse‘formatshortg’

•  Toremoveannoyingspaces(line‐feeds)use‘formatcompact’

•  PossibletospecifymulRpleformatsaslongastheydon’tcontradicteachother

3.8

Page 9: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 10: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 11: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

I/O–MATLABData

  Examples(save):•  savefile1.matX; %SavevariableXtofile1.mat•  save(filename,‘X’);%SaveXtoafilewhosenameis

storedinthevariable‘filename’

•  savefile1.matXYZ;%SaveX,Y,Ztofile1.mat

3.11

Page 12: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 13: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 14: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 15: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 16: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

Exercise(InClass)

  Loadingandsavingasequenceoffiles.  Supposeyouhaveadirectory‘home/mydata’whichcontains100filesallnamed‘dataset_#.mat’.EachfilesstoresamatrixM.WriteafuncRonthattakesaninputparameterN,andopenseachfile(from1toN),sortsthematrixMinroworder,andsavethesortedmatrixtoanewfilenamed‘newdata_#.mat’

3.16

Page 17: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

BasicPloJng

  ThegeneralfuncRonwewilluseisplot()•  ThefuncRonautomaRcallygeneratesafigureforyou

  TherearemanyopRonsavailable:•  CanspecifytheproperResoftheplotindetail•  CanhavemulRplecurvesonthesameplot

•  CanhavemulRpleplotsinonefigure•  MoreinteresRngplotsarepossiblewithbar(),pie()

3.17

Page 18: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 19: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 20: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 21: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 22: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

BasicPloJng–Figures

  MulRpleplots:•  plot(x,y);holdon;plot(x,z);holdoff;

  MulRpleplots,samefigure:•  subplot()command

•  figure(1);subplot(2,2,1);

3.22

Page 23: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 24: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 25: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 26: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

Exercise(InClass)

  Simpleplot

  WriteafuncRonthathasoneinputparameterM,amatrixwith3columns.Columns{1,2}ofMarethe{x,y}coordinatesofpointsintheplane.Column3istheclasstowhichthepointbelongs.Thevaluesofcolumn3areoneoftwounknownintegers

  YourfuncRonshouldplotallpoints,pointsinoneclassshouldbedotsinred,pointsinthe2ndclassshouldbesquaresingreen.Adjustyouraxesproperlysothatthefurthestpointsarenotontheedge

3.26

Page 27: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 28: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 29: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 30: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 31: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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

Page 32: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

Strings–FuncRons

  MATLABisnotrecommendedasatoolformanipulaRngstrings.However,thefuncRonalityisavailable

  Checkstring:•  isleBer(str),isspace(str)

  Convertstring:•  lower(str),upper(str)•  str2num(str),num2str(num)

3.32

Page 33: COMS 3101 Programming Languages: MATLAB Lecture 3vovsha/coms3101/matlab/mlab_lec3.pdf · Lecture Outline Loading and saving data More input/output Basic plong, figures Data structures:

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