Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
COMS3101ProgrammingLanguages:MATLAB
Lecture6
Fall2013Instructor:IliaVovsha
hCp://www.cs.columbia.edu/~vovsha/coms3101/matlab
LectureOutline
Review:HW4
PracOcalmath/opOmizaOon(conOnued) AdvancedfuncOonality:
• convhull(),inpolygon(),polyarea()
• triplot(),fill()
• mldivide(\),linprog()
• sortrows()• Convexity
6.2
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
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
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
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
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
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
3DSurface–Example
surfvs.mesh
Exercise(InClass)
Sets&handles WriteafuncOonwith3inputparameters{A,B,|},whichappliesthefuncOonstoredinthehandle‘|’tothevectors/matricesstoredin{A,B}.YoucanassumethatthefuncOonin‘|’canonlybeoneofthe“set”methods(union,intersect,setdiff,ismember)
6.10
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
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
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
FuncOonHandles@
PurposeoffuncOonhandles:• Supposetheusershouldbeabletochoosewhichsub‐
rouOnetouse.Thus,amechanismtopassaparameterwhichspecifiesthesub‐rouOneisrequired
• Can’tpassafuncOon,sopassahandleinstead• AlsopossibletodefinefuncOonsonthefly(anonymous
funcOons):
1. sqr=@(x)x.^2;2. a=sqr(5);
6.14
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
VariableInputArguments
FuncOonwhichcanhaveanynumberofinputargs
Rules:• Keyword:varargin
• ‘varargin’isacellarraycontainingtheopOonalargumentsONLY
• Mustbedeclaredasthelastinputargument• Mustbelowercase
• Example:“funcOonmy_fun(x,y,z,varargin)”
• Similarly,usevarargouttocreateafuncOonwithanynumberofoutputargs.Thesamerulesapply(last,lowercase)
6.16
TheMATLABHeist
Supposeyouaretryingtostealavaluableobjectfromaroom.TheroomisprotectedbyalasergridwhichfuncOonsasacloakofinvisibility.Eachlaserdotisconnectedtoeveryotherdot,andeachtripleofdotsensuresthatthetriangledefinedbythemisinvisible
YouhaveamapwhichspecifiesthelocaOonofeachlaserdotintheroom.YourgoalistoturnoffpartsofthegridunOltheobjectbecomesvisible.Toturnoffapart,youneedto“unravel”eachdotinthetriangle
6.17
TheMATLABHeist
However,unravelingsomedotsrequiresmoreOmethanothers.Thisisreflectedbyavalue(inseconds)aCachedtoeachdot.
Moreover,youneedtounravelagivendoteachOmeyouwishtoturnoffatriangleforwhichitisavertex
Nottobemisled,youshouldcheckwhethertheareayouaresearchingisindeedvisible
Youcanstopwhentheobjectisfound.Thatis,youmaynotneedtoturnoffeverytriangle
6.18
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
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
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
ConvexSet
Defini4on:asetofpointsCisconvex,ifthelinesegmentbetweenanytwopointsinCliesinC
Formally,ifforany{x,y}inCandany0≤w≤1,
wx+(1‐w)yisinC,thenCisconvex ImplicitlyassumingthatCisasubsetofthen‐dimensionalrealspace
WecangeneralizethedefiniOontoholdformorethantwopoints
6.22
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
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
2ndStep–Remark
Built‐infuncOonalitysimplifiesworkconsiderably
ThealternaOveistodefineandsolvelinearequaOons(mldivide,linprog)
6.25
PlosngGrid&Triangles
RecallthatMisanN‐by‐2(N≥3)matrixspecifyingthecoordinatesofthegrid.Everypairofdotsisconnected
Toploteverytriangle,wefirstneedtocreatealistoftriples.Eachtriplespecifiesthree(non‐collinear)dotsonthegrid
Built‐infuncOontoplottriangles:triplot() Built‐infuncOontocomputetripleswithoutloops:combntns()
6.26
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
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
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
CompuOngConvexHull
GivenasetofpointsinN‐D,compuOngthehullisnotatrivialtask.Severalalgorithmsareavailable
TheopOmalalgorithmmaydependontheproperOesofthepoints
Built‐infuncOons:convhull(),convhulln() Thehullisspecifiedbyasetof‘outerboundary’points
6.30
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.
PolygonInteriorCheck
Polygon:aplaneshapeconsisOngofstraightlinesthatarejoinedtogethertoformacircuit
Theconvexhullforasetof2Dpointsisapolygon.Atriangleisthesimplestpolygon
Tocheckwhetherapointisinsidethehull/triangleweneedtodefinethepolygonalregionandcheckifthepointisintheinterior
Built‐infuncOontocheck:inpolygon() Anotherapproach:solveasetoflinearequaOonsusinglinprog()
6.
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.
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
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.
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.
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.
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.
ChoosingaStrategy
Weneedastrategy(setofrules)toselectwhichtriangletoturnoffnext
Greedyalgorithmmakesthedecisionthatgivesthemaximumbenefitintheimmediatenextstep(locallyopOmal).Thisdecisionmightnotbethebestconsideringmore(all)steps(globallyopOmal)
Greedystrategy1:choosethelargesttriangle• Built‐infuncOontocomputearea:polyarea()
Greedystrategy2:choosetheleast‐efforttriangle• SumtheOmetounraveltheverOcesforeachtriangle
6.
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.
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.
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.
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.
Conclusion
High‐levellanguage:built‐infuncOonalityatyourfingerOps.EasytobypasseventhemosttrivialmathemaOcalproblemse.g.howdoyoucomputetrianglearea?Idon’tknow,butIdon’tcare,canjustusepolyarea()
Convenientpla�ormforprototyping.Maywishtodesignanelaborategame.CanaddrouOnesonea�eranotherwhileverifyingoutcomeusingplots.AllthisdoesnotrequireconsiderableOmeinvestment
6.