coms 3101 programming languages: matlab lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · coms 3101...

35
COMS 3101 Programming Languages: MATLAB Lecture 5 Fall 2013 Instructor: Ilia Vovsha hCp://www.cs.columbia.edu/~vovsha/coms3101/matlab

Upload: others

Post on 14-Oct-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

COMS3101ProgrammingLanguages:MATLAB

Lecture5

Fall2013Instructor:IliaVovsha

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

Page 2: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

LectureOutline

  Review:HW#3

  PracOcalmath/opOmizaOon(conOnued)  AdvancedfuncOonality:

  Time,error,sets

  FuncOonhandles

  VariablenumberoffuncOonarguments

  3D&areaplots

5.2

Page 3: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

UsefulRemarks

  SupposetheobjecOveistoaccessallrowsofamatrix(M)whichsaOsfysomecondiOon.Insteadofusing‘find’,candirectlytestforthecondiOon,andthenusethe0‐1‘logical’vectortoaccessrelevantrows

  Example:1.  pts=M(:,3)>=5 %ptsisa0/1‘logical’vector

2.  plot(M(pts,1),M(pts,2)) %plodngrowk,onlyifpts(k)==1

5.3

Page 4: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

HW#3

  ForHW3b,assumpOonswere:vectorCoflengthtwowithdisOnctvalues:1.  iflength(C)~=22.  return;

3.  end

4.  ifC(1)==C(2)

5.  return;

6.  end

  Whydowecheck“length(C)~=2”first?•  “if(length(C)~=2||C(1)==C(2))”isalsoOK

5.4

Page 5: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

LoadingData

  Threestepprocess:1.  IdenOfythetypeofdatayouhave2.  FindtherelevantfuncOon(s)

3.  Choosetheappropriateformat

  Example:“Eachfilehasstrictlynumericdataseparatedbydelimiter…rangeofdataisspecified”•  Step2:dlmread(),dlmwrite()

•  Step3:“RESULT=DLMREAD(FILENAME,DELIMITER,RANGE)”

•  ReadstherangespecifiedbyRANGE=[R1C1R2C2]

5.5

Page 6: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

num2cell()

  Problem1:createavector‘V’oflengthN,whereeachelement,V(k)=2^k

  Problem2:createacellarray‘C’oflengthN,whereeachelement,C{k}=2^k

  SoluOon(1):1.  idx=1:N;

2.  V=2.^idx; %Thedotisrequiredhere  SoluOon(2):

•  Cellarray,soluOon(1)doesn’twork!

•  Insteadofusingafor‐loopcouldconvertnumericarraytocell

5.6

Page 7: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

num2cell()

  Problem2:createacellarray‘C’oflengthN,whereeachelement,C{k}=2^k

  SoluOon(2):1.  idx=1:N;2.  V=2.^idx; %Visanumericarray

3.  C=num2cell(V); %ConvertedVtoacellarrayC

5.7

Page 8: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

BuildingaWinningTeam

  Considerthefollowingscenario:youareamanagerthatmustassembleateamofplayers.YouhaveascouOngreportdescribingthesetofskillsofeachplayer,andthesalarydemandsofeach

  Yourgoalistochooseyourteamfromalargepoolofplayers,ensuringthatyourplayerscomplementeachother

  SinceyourownerissOngy,youmustalsominimizeyourtotalplayersalary,whilemaintainingacompeOOveteam

5.8

Page 9: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

BWT–ProblemFormulaOon

  Morespecifically:•  YourteamshouldconsistofPplayers•  YouhaveapoolofNplayers(N≥P)tochoosefrom

•  Eachplayer‘p’,demandsasalaryofC(p)

•  ThescouOngreportconsistsofKmarksforeachplayer.Eachmarkisarealvalueintherange[0.0,1.0]indicaOngtheplayer’squalitywithrespecttoaparOcularskill(i.e.0.0is‘noob’,1.0is‘worldclass’)

•  ToensureacompeOOveteam,yourequirethatthetotalqualityofallteamplayersforeveryskill‘k’isatleastsomevalueB(k)

  Givenalltherelevantinfo(playerpool,salarydemands,scouOngreport),howdoyouchooseasetofPplayers,makeyourownerhappy,andsOllhaveacompeOOveteam?

5.9

Page 10: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

BWT–ProblemFormulaOon

  AssumpOons:•  Teamsize=P,Poolsize=N,(N≥P)•  C(salary)isanN‐by‐1(column)vectorofposiOverealvalues

•  RisanN‐by‐Kmatrixofrealvaluesintherange[0.0,1.0].Eachrowrepresentsaplayerinthepool.Eachcolumnrepresentsaskill

•  B(totalquality)isa1‐by‐K(row)vectorofposiOverealvalues

  Alltherelevantinfoisgiven.Thatis,{P,N,C,R,B}mustbesuppliedtous

  Note:noguaranteethattheparametersaresetcorrectly

  Note:cannothave‘half’aplayeronateam.Theplayeriseithersignedornot

5.10

Page 11: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

OpOmizaOon

  “Dothingsbestunderthegivencircumstances”

  ApplicaOonsinalmosteveryfieldimaginable:planning,scheduling,resourceallocaOon,management,trafficcontrol

  OpOmizaOonproblem:•  Makeadecision

•  Express/controlthequalityofthedecisionbytheobjecOvefuncOon

•  TypicallyaminimizaOon/maximizaOontask

•  Express“circumstances”thataffectthedecisionasconstraints

•  Thetypeofopt.prob.isdeterminedbythenatureoftheobjecOvefuncOonandtheconstraints

5.11

Page 12: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

OpOmizaOon–GeneralForm

GeneralFrom:

minimize F(x) subjectto: gi(x)≤bi i=1,…,m

  TheproblemischaracterizedbytheobjecOvefuncOonF(x),andtheconstraintsgi(x)

  Thevariableorvectorx,belongstosomedomain/setSspecifiedbytheconstraints

  LinearandQuadraOcprogramsarethemostfrequentproblemsyouarelikelytoencounter

5.12

Page 13: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

MATLABOpOmizaOonToolbox

  Extensivepackage.ManyrouOnes,opOons.PlentyofdocumentaOon(‘help’isnotsufficient)•  Firststep:defineyourproblemclearly,writedownyour

equaOons

•  Secondstep:findtheappropriatesolver(whattypeofproblemareyousolving?)

•  Thirdstep:convertyourproblemtosolverform.ThismightrequirecombiningequaOons,switchingsignofequaOons&objecOve,addingequaOons

•  Fourthstep:setopOons,callsolver,examinethesoluOon

5.13

Page 14: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

1stStep–Approach

  Approach:1.  Collectallparameters{P,N,C,R,B} %Input/loaddata2.  Verifythatparametersaresetcorrectly %Errorchecking

3.  StatetheprobleminmathemaOcalnotaOon:

•  WeareclearlysolvingaconstrainedopOmizaOonproblem

•  WearetryingtominimizealinearobjecOve(minimizethetotalsalary),subjectto:

•  Oneequalityconstraint,ateamshouldhaveexactlyPplayers•  Klinearinequalityconstraints(totalqualityforsomeskillisone

constraint,wehaveKskills)

•  Ourvariablesmustbebinary{0,1},cannotsign‘half’aplayer

4.  Output/verifythesoluOon %Output/savesoluOon

5.14

Page 15: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

1stStep–NotaOon

  MathemaOcalnotaOon:1.  LetXbethevariable/soluOon(column)vector,X∈{0,1}N2.  WewishtominimizetheobjecOvefuncOonCTX

3.  Oneequalityconstraint:∑Xi=P

4.  Klinearinequalityconstraints:RTX≥BT

5.  Completeform:

minimize CTX subjectto: RTX≥BT 1TX=P

∀p,Xp∈{0,1}

5.15

Page 16: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

2ndStep–ChooseSolver

  Findappropriatesolver:•  hCp://www.mathworks.com/help/toolbox/opOm/ug/

bqnk0r0.html

•  Frequentsolvers:linprog(),quadprog(),fmincon()

  Solverformexample:•  Linearprogram

minxf T x such that

A ⋅ x ≤ b,Aeq ⋅ x = beq,lb ≤ x ≤ ub

5.16

Page 17: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

3rdStep–SolverForm

  MATLABToolboxnotaOon:•  Appropriatesolver:bintprog()•  Why?SoluOonvectorisabinaryintegervector,objecOveislinear

andtheconstraintsarelinear

•  Converttosolverform:

1.  f=C;

2.  A=‐R’; %Changesign,transpose3.  b=‐B’; %Changesign,columnvector

4.  Aeq=ones(1,length(C)); %1TX=P

5.  beq=P; €

minxf T x such that

A ⋅ x ≤ b,Aeq ⋅ x = beq,x is binary

5.17

Page 18: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

4thStep–CallSolver

  Convertedtosolverform,variables{f,A,b,Aeq,beq}

  FuncOoncallopOons(syntax):x=bintprog(f)x=bintprog(f,A,b)x=bintprog(f,A,b,Aeq,beq)x=bintprog(f,A,b,Aeq,beq,x0)x=bintprog(f,A,b,Aeq,Beq,x0,opOons)x=bintprog(problem)[x,fval]=bintprog(...)[x,fval,exi�lag]=bintprog(...)[x,fval,exi�lag,output]=bintprog(...)

5.18

Page 19: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

GeneralSolverRules

  Syntaxrules(forallsolvers):•  Parameternotpassed,assumeitisempty•  Parameterorderisimportant

•  Toincludeasubsequentparameter,butomitaprecedingone,passanemptyarray[]

•  ‘opOons’isastructspecifyingopOmizaOonmethoddetails.Ignoreit,unlessyouknowathingortwoaboutthefield

•  Insteadofpassingmanyparameters,canpassasinglestruct‘problem’withappropriatefields

•  OutputparametersincludesoluOon(x),valueofobjecOvefuncOonatthesoluOon(fval),flagindicaOngoutcomeofcall(exi�lag),anddetailsabouttheexecuOon(output)

5.19

Page 20: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

bintprog()–Examples

  Parameternotpassed,assumeitisempty:•  x=bintprog(f) %MinimizeobjecOvewithoutconstraints

  Includesubsequentparameter,omitprecedingone:•  x=bintprog(f,[],[],Aeq,beq) %Noinequalityconstraints

  Passasinglestruct:1.  problem.f=C;

2.  problem.Aineq=‐R’;3.  problem.solver=‘binprog’;

4.  x=bintprog(problem);

•  NoOcethatfieldnamesareslightlydifferent

•  Mustsetallfieldsexceptx0(settoemptyifdoesn’texist)

5.20

Page 21: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

bintprog()–Examples

  Outputparameters: •  ‘x’:thesoluOonvector•  ‘exi�lag’:ifreturns1,problemsolvedsuccessfully

•  ‘output’:astructurewithsoluOondetails.Forexample,output.OmeisexecuOonOme

•  Cannameparametersinanywayyouwish

•  [soln,fval,the_flag,soln_details]=binprog(problem)

•  IfsoluOonvectorisnotwhatitshouldbe,youmustcheckalloutputparameterstodiscovertheproblem.Youshouldstartwiththe‘exi�lag’,thoughthereisnoprescribedapproachtodetectaproblem

5.21

Page 22: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

Time

  StopwatchtorecordelapsedOme(inseconds):•  ‘Oc’tostartthestopwatch•  ‘toc’tostopit

  Examples:1.  Oc;%codetoc; %DisplayselapsedOme2.  t1=Oc; %code t2=toc(t1) %StoreselapsedOmein‘t2’

3.  Oc;%codetoc;

%codetoc; %2ndtocdisplayselapsedOmesinceOc!

  Canalsoobtaindate,CPU‐Ome(clock,cpuOme,datestr)

5.22

Page 23: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

Error

  TohandleerrorsandabortexecuOon:•  error(‘somemessage’)%AbortsexecuOonandprintsthemessage

  More‘sophisOcated’errormessages:•  error('msgString',v1,v2)

•  Assumesmessagestringcontainsformatspecifiers(%s,%d)•  Replaceseachspecifierwiththeappropriateparameter

  “Catch”errors:•  “Try”somecode,ifyou“catch”anerror,overridedefaultcode

1.try

2. %testcode

3.catchexcepOon

4. %errorcode;

5.end

5.23

Page 24: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

Sets

  RelevantfuncOons:unique(),intersect(),union(),setdiff(),ismember()

  Generalform:•  <funcOon>(A,B) %AppliesfuncOontovectors{A,B}•  <funcOon>(A,B,‘rows’) %AppliesfuncOontomatrices{A,B}

•  [C,IA,IB]=<funcOon>(…) %ReturnscombinaOon&indices

  Rules:•  If{A,B}arematrices,mustsupplythe‘rows’parameter

•  {A,B}musthavethesamenumberofcolumns

  ismember(A,B):returnsa0/1arraywiththesizeofA.Whereelementissetto1ifelementisinB

5.24

Page 25: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

Sets–Examples

  Define:V1=[1,2,3,4];V2=[0,1,2];  Define:A1=[1,0;1,1;1,2];A2=[1,1;1,1;1,2];  Examples:

1.  ans=intersect(V1,V2)

2.  ans=union(V1,V2)

3.  ans=union(A1,A2)

4.  ans=setdiff(V1,V2) 5.  ans=ismember(A1,1)

6.  ans=ismember(V1,[‐1,2,4])

5.25

Page 26: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

textscan()

  ReadformaCeddatafromatextfile

  textread()isanother(deprecated)funcOonwithsimilarfuncOonality

  Howdoesitwork?•  C=textscan(FID,'format')

•  Recallthattoopenatextfile,weneedtocreateanidenOfier:FID=fopen(‘myfile.text’,‘r’);

•  ‘format’isastringspecifyinghoweachlineshouldberead

•  ‘C’isacellarray.Thenumberofspecifiers(‘format’)determinesthenumberofcells

5.26

Page 27: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

FuncOonHandles@

  FuncOonhandle:avariablethatstoresanidenOfierforafuncOon•  h1=@min; %‘h1’cannowbeusedinsteadof‘min’

•  val=h1(rand(3)) %Sameasval=min(rand(3))

  Canusehandlesincellarraysorstructs,butnotinregulararrays:•  C={@min,@max,@mean};

•  S.a=@min;S.b=@max;S.c=@mean;•  A=[@min,@max]; WRONG!

5.27

Page 28: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

FuncOonHandles@

  PurposeoffuncOonhandles:•  Supposetheusershouldbeabletochoosewhichsub‐

rouOnetouse.Thus,amechanismtopassaparameterwhichspecifiesthesub‐rouOneisrequired

•  Can’tpassafuncOon,sopassahandleinstead•  AlsopossibletodefinefuncOonsonthefly(anonymous

funcOons):

1.  sqr=@(x)x.^2;2.  a=sqr(5);

5.28

Page 29: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

Exercise(InClass)

  Sets&handles  WriteafuncOonwith3inputparameters{A,B,�},whichappliesthefuncOonstoredinthehandle‘�’tothevectors/matricesstoredin{A,B}.YoucanassumethatthefuncOonin‘�’canonlybeoneofthe“set”methods(union,intersect,setdiff,ismember)

5.29

Page 30: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

VariableInputArguments

  FuncOonwhichcanhaveanynumberofinputargs

  Rules:•  Keyword:varargin

•  ‘varargin’isacellarraycontainingtheopOonalargumentsONLY

•  Mustbedeclaredasthelastinputargument•  Mustbelowercase

•  Example:“funcOonmy_fun(x,y,z,varargin)”

•  Similarly,usevarargouttocreateafuncOonwithanynumberofoutputargs.Thesamerulesapply(last,lowercase)

5.30

Page 31: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

Exercise(InClass)

  Variableinputarguments

  WriteafuncOonwithatleast3inputparameters{A,B,�1,�2,�3…},whichappliesthefuncOonsstoredinthehandles‘�1’(�2,�3…ifpresent)tothevectors/matricesstoredin{A,B}.YoucanassumethatthefuncOonin‘�#’canonlybeoneofthe“set”methods(union,intersect,setdiff,ismember)

5.31

Page 32: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

MorePlodng–3D

  Verysimilarto2Dplodng

  Keyword:plot3()  Example:1.X=0:0.1:1;Y=X;Z=X.^2+Y.^2;

2.plot3(X,Y,Z);3.xlabel(‘locX’);ylabel(‘locY’);zlabel(‘power’);

4.xlim([01]); zlim([040]);

5.32

Page 33: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

MorePlodng–Surface

  ‘plot’funcOonsproducelineplots.Supposewewishtodisplaya3Dsurface

  Keywords:meshgrid(),mesh(),surf()

  Thecommandmeshgrid(X,Y)createsagrid(domain)withallcombinaOonsof{X,Y}elements.mesh(X,Y,Z)/surf()arethenusedtoplotthesurfaceZ=f(X,Y)overthegrid

5.33

Page 34: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

3DSurface–Example

  Example:1.X=1:4;Y=1:3;2.[Xg,Yg]=meshgrid(X,Y); %produceagrid

3.Z=X.^2+Y.^2; %Z=f(X,Y)4.mesh(X,Y,Z); %plot

5.surf(X,Y,Z); %plot  ‘mesh’plotswireframe.‘surf’plotswithshading

  Canpassa4thparameterspecifyingcolore.g.“surf(X,Y,Z,C)”.Otherwise,colorisproporOonaltomeshheight

5.34

Page 35: COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101 Programming Languages: MATLAB ... • ‘output’: a structure with soluon details

3DSurface–Example

  surfvs.mesh