COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101...
Transcript of COMS 3101 Programming Languages: MATLAB Lecture 5vovsha/coms3101/matlab/mlab_lec5.pdf · COMS 3101...
![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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/1.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/2.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/3.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/4.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/5.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/6.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/7.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/8.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/9.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/10.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/11.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/12.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/13.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/14.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/15.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/16.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/17.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/18.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/19.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/20.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/21.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/22.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/23.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/24.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/25.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/26.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/27.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/28.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/29.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/30.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/31.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/32.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/33.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/34.jpg)
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.](https://reader033.fdocuments.net/reader033/viewer/2022053022/604d0420ea0b916663294614/html5/thumbnails/35.jpg)
3DSurface–Example
surfvs.mesh