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

COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

COMS3101ProgrammingLanguages:MATLAB

Lecture6

Fall2013Instructor:IliaVovsha

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

Page 2: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

LectureOutline

  Review:HW4

  PracOcalmath/opOmizaOon(conOnued)  AdvancedfuncOonality:

•  convhull(),inpolygon(),polyarea()

•  triplot(),fill()

•  mldivide(\),linprog()

•  sortrows()•  Convexity

6.2

Page 3: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

UsefulRemarks

  Tocheckwhetheravariable‘h’isafuncOonhandle:•  isa(h,‘funcOon_handle’)

  “&,|”vs.“&&,||”•  Asinglesymbol{&,|}canoperateonarrays

•  Thedoublesymbol{&&,||}providesforshort‐circuitbehavior•  Short‐circuitbehavior:stopevaluaOngastatementwhentheoutcome

isclear

•  Examples:

1.  if(b>0)&&(a/b)>1 %don’tevaluatea/bifb<=0

2.  R=A1&A2 %R(1)=A1(1)&A2(1); %R(2)=A1(2)&A2(2);...

6.3

Page 4: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

HW4

  Normalizeavector‘V’tothe[0,1]range:•  V=(V‐min(V)/(max(V)–min(V))

  Checkasetoffieldsforastruct:•  ck=isfield(specs,{‘f1’,‘f2’,‘f3’})

  Checkforanon‐emptystringvariable‘fdir’:•  str_ck=isstr(fdir)&~isempty(fdir);•  str_ck=ischar(fdir)&~isempty(fdir);

  CheckforaposiOveintegervariable‘N’:•  int_ck=isnumeric(N)&(round(N)==N)&(N>0);

6.4

Page 5: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

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

6.5

Page 6: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

MorePlosng–3D

  Verysimilarto2Dplosng

  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]);

6.6

Page 7: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

MorePlosng–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

6.7

Page 8: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

3DSurface–Example

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

3.Z=Xg.^2+Yg.^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.

6.8

Page 9: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

3DSurface–Example

  surfvs.mesh

Page 10: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

Exercise(InClass)

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

6.10

Page 11: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

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

6.11

Page 12: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

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])

6.12

Page 13: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

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!

6.13

Page 14: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

FuncOonHandles@

  PurposeoffuncOonhandles:•  Supposetheusershouldbeabletochoosewhichsub‐

rouOnetouse.Thus,amechanismtopassaparameterwhichspecifiesthesub‐rouOneisrequired

•  Can’tpassafuncOon,sopassahandleinstead•  AlsopossibletodefinefuncOonsonthefly(anonymous

funcOons):

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

6.14

Page 15: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

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)

6.15

Page 16: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

VariableInputArguments

  FuncOonwhichcanhaveanynumberofinputargs

  Rules:•  Keyword:varargin

•  ‘varargin’isacellarraycontainingtheopOonalargumentsONLY

•  Mustbedeclaredasthelastinputargument•  Mustbelowercase

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

•  Similarly,usevarargouttocreateafuncOonwithanynumberofoutputargs.Thesamerulesapply(last,lowercase)

6.16

Page 17: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

TheMATLABHeist

  Supposeyouaretryingtostealavaluableobjectfromaroom.TheroomisprotectedbyalasergridwhichfuncOonsasacloakofinvisibility.Eachlaserdotisconnectedtoeveryotherdot,andeachtripleofdotsensuresthatthetriangledefinedbythemisinvisible

  YouhaveamapwhichspecifiesthelocaOonofeachlaserdotintheroom.YourgoalistoturnoffpartsofthegridunOltheobjectbecomesvisible.Toturnoffapart,youneedto“unravel”eachdotinthetriangle

6.17

Page 18: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

TheMATLABHeist

  However,unravelingsomedotsrequiresmoreOmethanothers.Thisisreflectedbyavalue(inseconds)aCachedtoeachdot.

  Moreover,youneedtounravelagivendoteachOmeyouwishtoturnoffatriangleforwhichitisavertex

  Nottobemisled,youshouldcheckwhethertheareayouaresearchingisindeedvisible

  Youcanstopwhentheobjectisfound.Thatis,youmaynotneedtoturnoffeverytriangle

6.18

Page 19: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

Heist–ProblemFormulaOon

  Morespecifically:•  Theroomisdefinedbythe2Dsquare[0.0,1.0],[0.0,1.0]•  ThegridisdefinedbyasetofNlaserdots(N≥3)

•  Eachdot‘n’,requiresC(n)secondstounravel

•  ThelocaOonofeachdot‘n’isspecifiedbytwocoordinates{xn,yn}Bothcoordinatesareintherange[0.0,1.0]

•  Tovisualizethegrid,wecanconnecteverypairofdotswithastraightline

  Giventhecompletegrid,howdoyouchoosewhichpartsofthegridtoturnoff?HowmuchOmedoesittaketofindtheobject?

6.19

Page 20: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

Heist–ProblemFormulaOon

  AssumpOons:•  MisanN‐by‐2(N≥3)matrixspecifyingthegrid•  Columns{1,2}ofMarethe{x,y}coordinatesofthedotsrespecOvely

•  C(Ome)isanN‐by‐1(column)vectorofposiOverealvalues

•  Mconsistsofrealvaluesintherange[0.0,1.0]

  Alltherelevantinfoisgiven.Thatis,{M,N,C}mustbeknown  Note:noguaranteethattheparametersaresetcorrectly

  Note:thereisnoaprioriinformaOonaboutthelocaOonoftheobjectintheroom

6.20

Page 21: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

1stStep–Approach

  Approach:1.  Collectandverifyallparameters{M,N,C}2.  Generatesomeplots:grid(2D),gridvs.Ome(3D),progress(2D

triangles)

3.  Decideonasearchstrategy:

I.  DeterminewhetherthestarOngpointisintheconvexhullforthegrid.

II.  Choosewhichtriangletoturnoff(e.g.minimizeeffortormaximizetrianglearea)

III.  CheckwhethertheareayouaresearchingisvisibleIV.  Updateyourstrategyifnecessaryandkeeptrackofprogress

4.  Evaluateyourstrategyinhindsight

6.21

Page 22: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

ConvexSet

  Defini4on:asetofpointsCisconvex,ifthelinesegmentbetweenanytwopointsinCliesinC

  Formally,ifforany{x,y}inCandany0≤w≤1,

wx+(1‐w)yisinC,thenCisconvex  ImplicitlyassumingthatCisasubsetofthen‐dimensionalrealspace

  WecangeneralizethedefiniOontoholdformorethantwopoints

6.22

Page 23: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

ConvexHull

  Defini4on:wecallapoint‘p’oftheformp=w1x1+w2x2+…+wkxk,wherew1+w2+…+wk=1andwi≥0(∀i),aconvexcombina4onofthepoints{x1,…,xk}.

  Convexcombina4on:weightedaverageofthepoints  Defini4on:thesetofallconvexcombinaOonsofpointsinCiscalledtheconvexhullofC

  Convexhull:ThesmallestconvexsetthatcontainsC  ThesenoOonscanbeappliedtoinfinitesumsandnon‐Euclideanspacesaswell

6.23

Page 24: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

2ndStep–ConcreteTasks

  Problems&relevantfuncOonality:1.  Generateplots:grid(plot,triplot),gridvs.Ome(plot3)2.  Computeconvexhull:usegriddata(convhull)

3.  Chooseatriangletoturnoff:maximizearea(polyarea)orminimizeeffortbyrecordingeverytriangleandvalueandthensorOng(sortrows)

4.  Checkifareaisvisible:verifywhetheragivenlocaOonisinsideatriangle(inpolygon)

5.  Keeptrackofprogress:markvisibletriangles(fill)

6.24

Page 25: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

2ndStep–Remark

  Built‐infuncOonalitysimplifiesworkconsiderably

  ThealternaOveistodefineandsolvelinearequaOons(mldivide,linprog)

6.25

Page 26: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

PlosngGrid&Triangles

  RecallthatMisanN‐by‐2(N≥3)matrixspecifyingthecoordinatesofthegrid.Everypairofdotsisconnected

  Toploteverytriangle,wefirstneedtocreatealistoftriples.Eachtriplespecifiesthree(non‐collinear)dotsonthegrid

  Built‐infuncOontoplottriangles:triplot()  Built‐infuncOontocomputetripleswithoutloops:combntns()

6.26

Page 27: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

combntns()

  Syntax:combos=combntns(set,subset)

  Ac)on:returnsamatrixwhoserowsarethevariouscombinaOonsofelementsfromvector‘set’.Eachcombo(row)isoflength‘subset’

  Example:•  combos=combntns(1:3,2) %“3choose2”

•  combos:

[12

13

23]

6.27

Page 28: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

triplot()

  Syntax:triplot(TRI,x,y)•  triplot(TRI,x,y,color)•  triplot(TRI,x,y,‘param’,‘value’)

  Ac)on:displaysthetrianglesdefinedintheN‐by‐3matrixTRI.ArowofTRIcontainsindicesintothevectorsx,ythatdefineasingletriangle.Thedefaultlinecolorisblue

  Example:•  x=rand(5,1);y=rand(5,1);•  combos=combntns(1:5,3); %“5choose3”

•  triplot(combos,x,y);

6.28

Page 29: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

3rdStep(Code)–Plots

  Codetogenerateplots:1.  X=M(:,1);Y=M(:,2); %griddots2.  figure(1); %Createfigure

3.  plot(X,Y,‘r.’,‘MarkerSize’,20); %plotdots

4.  figure(2);

5.  plot3(X,Y,M(:,3),‘r.’); %plotdotsvs.Ome

6.  figure(1);holdon; %Resettofigure17.  LT=combntns(1:length(X),3); %Listalltriangles

8.  triplot(LT,X,Y,'black'); %Plottriangles

6.29

Page 30: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

CompuOngConvexHull

  GivenasetofpointsinN‐D,compuOngthehullisnotatrivialtask.Severalalgorithmsareavailable

  TheopOmalalgorithmmaydependontheproperOesofthepoints

  Built‐infuncOons:convhull(),convhulln()  Thehullisspecifiedbyasetof‘outerboundary’points

6.30

Page 31: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

convhull()

  Syntax:[CH,V]=convhull(X,Y)  Ac)on:returnsthe2DconvexhullCHofthepoints(X,Y),whereXandYarecolumnvectors,andthecorrespondingarea/volumeVboundedbyK.‘CH’isavectorofpointindicesarrangedinacounter‐clockwisecyclearoundthehull

  Example:•  x=[0,1,0.5,1,0]’;y=[0,0,0.5,1,1]’;•  [CH,A]=convhull(x,y);%CH=[1,2,4,5,1]’,A=1.0(areaofsquare)

•  plot(x(CH),y(CH),'r‐',x,y,'b+')

6.

Page 32: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

PolygonInteriorCheck

  Polygon:aplaneshapeconsisOngofstraightlinesthatarejoinedtogethertoformacircuit

  Theconvexhullforasetof2Dpointsisapolygon.Atriangleisthesimplestpolygon

  Tocheckwhetherapointisinsidethehull/triangleweneedtodefinethepolygonalregionandcheckifthepointisintheinterior

  Built‐infuncOontocheck:inpolygon()  Anotherapproach:solveasetoflinearequaOonsusinglinprog()

6.

Page 33: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

inpolygon()

  Syntax:IN=inpolygon(X,Y,Px,Py)•  [INON]=inpolygon(X,Y,Px,Py)

  Ac)on:returnsa0/1matrix‘IN’thesamesizeasX&Y.IN(k)=1if{X(k),Y(k)}isinsidethepolygonorontheboundary.ThepolygonverOcesarespecifiedbythevectors{Px,Py}

  Example:•  Px=[0,1,1,0]’;Py=[0,0,1,1]’; %PolygonverOces

•  X=[0.1,0.2,0.5,1];Y=[0.1,0.2,1.1,0.8]; %Pointstotest •  IN=inpolygon(X,Y,Px,Py); %IN=[1,1,0,1]

6.

Page 34: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

3rdStep(Code)–InteriorCheck

  Codetocompute/plotconvexhullandcheckinterior:1.  X=M(:,1);Y=M(:,2); %griddots2.  figure(1);holdon;prop=‘MarkerSize’; %createfigure

3.  plot(X,Y,‘r.’,prop,20); %plotdots

4.  [CH,A]=convhull(X,Y); %computehull

5.  Px=X(CH);Py=Y(CH); %polygonverOces

6.  plot(Px,Py,‘g‐’,X,Y,‘r.’,prop,20); %plothull7.  IN_H=inpolygon(Ix,Iy,Px,Py); %{Ix,Iy}starOngpoint

8.  LT=combntns(1:length(X),3); %LTisthelistofTRG

9.  Tx=X(LT(k,:));Ty=Y(LT(k,:)); %triangleverOces

10.  IN_T=inpolygon(Ix,Iy,Tx,Ty); %checkifinsidetriangle

Page 35: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

HullInteriorCheck–SLE

  NoOcethateverypointinsidetheconvexhullisaconvexcombinaOon(weightedavg.)ofthepointsforwhichthehullwascomputed

  Inotherwords,ifpt={ptx,pty}isinsidethehull,thenforsomesetofweights{w1…wk}:1.  ptx=w1x1+w2x2+…+wkxk

2.  pty=w1y1+w2y2+…+wkyk3.  w1+w2+…+wk=1

4.  ∀i,wi≥0

  NeedtosolveasystemoflinearequaOons(SLE)withlowerboundsonthevariables

6.

Page 36: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

HullInteriorCheck–NotaOon

  StandardnotaOon:1.  ptx=w1x1+w2x2+…+wkxk2.  pty=w1y1+w2y2+…+wkyk

3.  w1+w2+…+wk=1

4.  ∀i,wi≥0

  VectornotaOon:1.  XTW=ptx2.  YTW=pty

3.  1TW=1

4.  W≥0

  Solverform:1.  [X;Y;1]TW=[ptx;pty;1]

2.  0≤W

6.

Page 37: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

SolvingSLE

  GivenasystemoflinearequaOonsAx=b,doesithaveasoluOon?

  DependsonthematrixA:1.  IfAisasquarematrix:x=A‐1b2.  Elsewehaveanunder/over‐determinedsystem

3.  CouldhavemulOple/nosoluOonsforeithercase

  TocomputetheinverseofAefficiently,candecomposethematrix.MulOplewaysofdoingthis(LU,QR)

  WhenAisnotsquare,canminimizenorm(A*X–B)i.e.,thelengthofthevectorAX–B.ThisistheleastsquaressoluOon

6.

Page 38: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

mldivide(\)

  Syntax:x=A\b•  x=mldivide(A,b)•  x=inv(A)*b

•  Ac)on:IfAisasquarematrix,A\bisroughlythesameasinv(A)*B.Otherwise,x=A\bistheleastsquaressoluOon.AwarningmessageisdisplayedifAisbadlyscaledornearlysingular

  Example:•  A=[X;Y;1]T;b=[ptx;pty;1]; %HullinteriorequaOons•  x=A\b; %SoluOontoSLE

6.

Page 39: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

ChoosingaStrategy

  Weneedastrategy(setofrules)toselectwhichtriangletoturnoffnext

  Greedyalgorithmmakesthedecisionthatgivesthemaximumbenefitintheimmediatenextstep(locallyopOmal).Thisdecisionmightnotbethebestconsideringmore(all)steps(globallyopOmal)

  Greedystrategy1:choosethelargesttriangle•  Built‐infuncOontocomputearea:polyarea()

  Greedystrategy2:choosetheleast‐efforttriangle•  SumtheOmetounraveltheverOcesforeachtriangle

6.

Page 40: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

polyarea()

  Syntax:A=polyarea(X,Y)  Ac)on:returnstheareaofthepolygonspecifiedbytheverOcesinthevectorsXandY.IfXandYarematricesofthesamesize,thentheareaiscomputedforeachcolumn(polygon)of{X,Y}

  Example:•  TSx=X(LT);TSy=Y(LT); %VerOcesforeverytriangle

•  T_area=polyarea(TSx',Tsy'); %Areaforeverytriangle

6.

Page 41: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

3rdStep(Code)–Strategy

  Codetoimplementstrategy:1.  X=M(:,1);Y=M(:,2);T=M(:,3); %griddots&Ome2.  LT=combntns(1:length(X),3); %LTisthelistofTRG

3.  TSx=X(LT);TSy=Y(LT); %verOces∀TRG

4.  T_area=polyarea(TSx',Tsy'); %area∀TRG

5.  Tot_effort=sum(T(LT),2); %totaleffort∀TRG

6.  choice=[LT,T_area',Tot_effort]; %Combineintoonemtx7.  top_choice=sortrows(choice,‐4); %sortrowsbyarea

8.  top_choice=sortrows(choice,[‐4,5]); %sortbyareathenbyOme

6.

Page 42: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

fill()

  Syntax:A=fill(X,Y,C)  Ac)on:fillsthepolygonwhoseverOcesarespecifiedin{X,Y}withtheconstantcolorspecifiedinC(Ccanbeasinglecharacterstringchosenfromthelist{r,g,b,c,m,y,w,k}oranRGBrowvectortriple,[rgb])

  Example:•  fill(X(LT(1,:)),Y(LT(1,:)),'m'); %fillonetriangle

•  fill(X(LT)',Y(LT)','m'); %filleverytriangle

6.

Page 43: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

3rdStep(Code)–Tracking

  Codetotrackprogress:1.  X=M(:,1);Y=M(:,2);T=M(:,3); %griddots&Ome2.  LT=combntns(1:length(X),3); %LTisthelistofTRG

3.  figure(1);holdon; %createfigure

4.  fill(X(LT)',Y(LT)','m'); %filleverytriangle

5.  triplot(LT,X,Y,'black'); %Plottriangles

6.  [CH,A]=convhull(X,Y); %computehull7.  plot(X(CH),Y(CH),‘g‐’,X,Y,‘r.’,prop,20); %plothull

6.

Page 44: COMS 3101 Programming Languages: MATLAB Lecture 6vovsha/coms3101/matlab/mlab_lec6.pdf• C (me) is an N‐by‐1 (column) vector of posive real values • M consists of real values

Conclusion

  High‐levellanguage:built‐infuncOonalityatyourfingerOps.EasytobypasseventhemosttrivialmathemaOcalproblemse.g.howdoyoucomputetrianglearea?Idon’tknow,butIdon’tcare,canjustusepolyarea()

  Convenientpla�ormforprototyping.Maywishtodesignanelaborategame.CanaddrouOnesonea�eranotherwhileverifyingoutcomeusingplots.AllthisdoesnotrequireconsiderableOmeinvestment

6.