coms 3101 programming languages: matlab lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · next...
TRANSCRIPT
![Page 1: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/1.jpg)
COMS3101ProgrammingLanguages:MATLAB
Lecture4
Fall2013Instructor:IliaVovsha
hCp://www.cs.columbia.edu/~vovsha/coms3101/matlab
![Page 2: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/2.jpg)
LectureOutline
Review:EHW#1,2
PloQng(figures) Datastructures:cellarrays,structs,strings,handles PracWcalmath:formulaWngandsolvingproblems
NextLecture:opWmizaWon NextLecture:FinalprojectoverviewandopWons NextLecture:advancedfuncWonality
4.2
![Page 3: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/3.jpg)
UsefulRemarks
Avoidmakingrepeatedcallstobuilt‐infuncWons
InsteadofaccessinganelementmanyWmes,justdefineanduseavariable:t=M(i,j)
Someprogramminglanguagesallowyoutoincrementvariablesusingtheoperators{++,‐‐}.ThisisnotanopWoninMATLAB
FuncWonsthatreturnaBooleanvariable(0/1)couldbeusedasthecondiWon:“ifisprime(N)”insteadof“ifisprime(N)==1”
CanusevectorsandmatricesincondiWonstoo
4.3
![Page 4: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/4.jpg)
UsefulRemarks
SoluWonsareposted(average:80+) MulWplymatrixMbyascalarC:
Answer:M*C %M.*Cisredundant
Noneedtoincrementtheloopvariableinsidethefor‐loop Ontheotherhand,incremenWngisoienessenWalinwhile‐
loops
Ifyoudefinedavariableforonepurpose,donotredefineitforanotherbelow.Thiscreatesunnecessaryconfusion
4.4
![Page 5: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/5.jpg)
SwitchStatement–Usage
When?• Morethan2‐3choices• Choiceisbasedonacommonexpression
How?switchswitch_expr %Expressionisascalarorastring
casecase_expr %Match‘case_expr’
statement(s)
case{case_expr1,case_expr2} %Matchanycaseinthearray
statement(s)
otherwise
statement(s)
end
4.5
![Page 6: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/6.jpg)
SwitchStatement–Usage
Brackets{}arenotrequiredunlessyouwishtoexecutethesamecodeformorethanonecase
‘break’statementsareredundant.UnlikeC++forexample,thereisno‘fallingthrough’
‘otherwise’isopWonal
4.6
![Page 7: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/7.jpg)
ASillyGame
Considerthefollowing‘game’:1. ChooseanyposiWveinteger(1,2,…),callitX2. IfXisanevenintegeryoudivideXby2
3. IfXisanoddintegeryoumulWplyXby3andadd1
4. ConWnuethisprocedureunWlatsomepointyouget1asyournextinteger.Atthatpointstop
Claim:thegameendsforeveryposiWveinteger Canyouprovetheclaim?Tryit!
4.7
![Page 8: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/8.jpg)
CollatzConjecture
DecepWvelysimple
ProposedbyCollatzin1937,sWllunsolved(!) “MathemaWcsisnotyetripeforsuchproblems”–PaulErdos
Thisconjecture/problemhasmanyversionsandnames
WecanuseMATLABtogeneratesomeplotsandperhapsobtainsomeinsight
4.8
![Page 9: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/9.jpg)
CollatzConjecture–Example
Problem:writeafuncWonthatgeneratesthesequencefromN(inputparameter)to1,accordingtothegame,andthenploteachpair(sequence#,value)onafigure
Forexample,ifX=3,thesequenceis{3,10,5,16,8,4,2,1}.Soyoushouldplotthepoints(1,3),(2,10),(3,5)…(8,1)
4.9
![Page 10: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/10.jpg)
CollatzConjecture–Example
SoluWon:1.Y=N; %IniWalize
2.whileN>1 %orN~=13. ifmod(N,2)==0 %Computesequence
4. N=N/2;
5. else
6. N=(N*3)+1;
7. end
8. Y(end+1)=N;
9.end
10.LY=length(Y);
11.X=1:LY;
12.plot(X,Y,'r.',X,Y,'b:’); %PlotredpointsanddoCedblueline
4.10
![Page 11: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/11.jpg)
BasicPloQng–Figures
Problem:• plot(x,y);plot(x,z);replaces1stplotwith2nd
SoluWon:‘figure’command• plot(x,y);figure;plot(x,z);
• figure(1);figurewithhandle#1
Closefigures:• Specificfigure:close1• Allfigures:closeall
MATLABstoresahandletoeachfigure
4.11
![Page 12: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/12.jpg)
BasicPloQng–Figures
MulWpleplots:• plot(x,y);holdon;plot(x,z);holdoff;
MulWpleplots,samefigure:• subplot()command
• figure(1);subplot(2,2,1);
4.12
![Page 13: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/13.jpg)
BasicPloQng–Appearance
ManyopWons,canmodifyplotsusingtheGUI
Commands:Wtle(),xlabel(),ylabel(),axis(),legend() Example:1.figure(1);
2.Wtle(‘test’);3.xlabel(‘quanWty’);ylabel(‘price’);
4.axis([15110]); %AXIS([XMINXMAXYMINYMAX])5.gridon; %Showgridlines
6.xlim([13]); %Changex‐axislimits
4.13
![Page 14: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/14.jpg)
BasicPloQng–Figures
YouhavecreatedmulWplefigures.Whichoneisthe‘currentfigure’?
Answer:lastfigureyouclickedon BeCeranswer:usegcf()togetthehandle Usefigure(#)tomake‘#’thecurrenthandle Commands:gcf(),gca(),clf() Set‘object’properWesusingtheset()command:
• set(gca,'XTick',[123]) %Toset‘Wcks’onthex‐axis
Get‘object’properWesusingtheget()command
4.14
![Page 15: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/15.jpg)
Saving&LoadingFigures
MATLABhasaspecialfigureformat:‘.fig’
Useopenfig(‘name.fig’)toopenasavedfigure Savingfigures:useprintcommand– GeneralForm
– print -dformat filename – Example – print –depsc ‘figure.eps’
‘eps’isaformatthatstoresyourimageinavectorizedway,whichavoidsqualitylossaierrescaling.It’sparWcularlyusefulwhenusedwithinLaTeX
4.15
![Page 16: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/16.jpg)
Exercise(InClass)
Simpleplot
WriteafuncWonthathasoneinputparameterM,amatrixwith3columns.Columns{1,2}ofMarethe{x,y}coordinatesofpointsintheplane.Column3istheclasstowhichthepointbelongs.Thevaluesofcolumn3areoneoftwounknownintegers
YourfuncWonshouldplotallpoints,pointsinoneclassshouldbedotsinred,pointsinthe2ndclassshouldbesquaresingreen.Adjustyouraxesproperlysothatthefurthestpointsarenotontheedge
4.16
![Page 17: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/17.jpg)
DataStructures–Structs
Whenacompositedatastructureisrequired,usea‘struct’(structurearray)• MulWplefields,differentdatastructuresforeachfield
• SimilarinformtoC++classes• Use‘dot’toaccessfields
IniWalizaWon:• S=struct([]) %Emptystruct,nofields
• S=struct(‘f1’,v1,‘f2’,v2) %Structwithtwofields• S.field1=2.5; %Createdirectly
4.17
![Page 18: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/18.jpg)
DataStructures–Structs
FuncWonality:• isstruct(S); %CheckifSisastruct• S=se�ield(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);
4.18
![Page 19: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/19.jpg)
Structs–Note
WhenmulWplevariablesaresavedina.matfile,andthenloadedintoasinglevariable,theyaresavedasfieldsofastruct
Example:1.savefile1.matXYZ;2.S=load(‘file1’);
3.isstruct(S); %Structwith3fields:S.X,S.Y,S.Z
4.19
![Page 20: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/20.jpg)
DataStructures–CellArrays
Cellarrayisan‘arrayofmatrices’.• Eachelementofacellarraycanbeascalar/vector/matrix.• Whyisituseful?Recallthe1stexercise(loadinga
sequenceoffiles)
IniWalizaWon:• C=cell(N) %NbyNarrayofemptymatrices• C=cell(N,M) %NbyMarrayofemptymatrices
• Usebrackets{}toaccesselements
• Rulesforregulararraysapply• C={[1][1,2,3];rand(3),rand(3)}; %Createdirectly
4.20
![Page 21: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/21.jpg)
CelltoStructConversion
Commands:cell2struct(),struct2cell()• S=cell2struct(C,my_fields,my_dim)• ‘my_fields’isacellarrayofstrings
Example:1.my_fd={‘num’,‘name’,‘naWon’};2.my_arr={8,‘Iniesta’,‘Spain’};
3.my_st=cell2struct(my_arr,my_fd,2);%Youare‘folding’thedimension,sizemustmatch
4.21
![Page 22: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/22.jpg)
Strings–FuncWons
MATLABisnotrecommendedasatoolformanipulaWngstrings.However,thefuncWonalityisavailable
Checkstring:• isleCer(str),isspace(str)
Convertstring:• lower(str),upper(str)• str2num(str),num2str(num)
4.22
![Page 23: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/23.jpg)
Strings–FuncWons
OperaWonsonstrings:• strtok(str,delim),strcmp(str1,str2),strfind(str1,paCern)
Regularexpressions(helpregexp):conciseandflexiblemeansformatchingstrings
Example:1.str1=‘one!,notwo’;2.[bef_delim,ai_delim]=strtok(str1,‘!’);
3.idx=strfind(str1,‘n’);4.res1=strcmp(‘hi’,‘HI’);
5.res2=strcmp(‘hi’,lower(‘HI’);
4.23
![Page 24: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/24.jpg)
BuildingaWinningTeam
Considerthefollowingscenario:youareamanagerthatmustassembleateamofplayers.YouhaveascouWngreportdescribingthesetofskillsofeachplayer,andthesalarydemandsofeach
Yourgoalistochooseyourteamfromalargepoolofplayers,ensuringthatyourplayerscomplementeachother
SinceyourownerissWngy,youmustalsominimizeyourtotalplayersalary,whilemaintainingacompeWWveteam
4.24
![Page 25: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/25.jpg)
BWT–ProblemFormulaWon
Morespecifically:• YourteamshouldconsistofPplayers• YouhaveapoolofNplayers(N≥P)tochoosefrom
• Eachplayer‘p’,demandsasalaryofC(p)
• ThescouWngreportconsistsofKmarksforeachplayer.Eachmarkisarealvalueintherange[0.0,1.0]indicaWngtheplayer’squalitywithrespecttoaparWcularskill(i.e.0.0is‘noob’,1.0is‘worldclass’)
• ToensureacompeWWveteam,yourequirethatthetotalqualityofallteamplayersforeveryskill‘k’isatleastsomevalueB(k)
Givenalltherelevantinfo(playerpool,salarydemands,scouWngreport),howdoyouchooseasetofPplayers,makeyourownerhappy,andsWllhaveacompeWWveteam?
4.25
![Page 26: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/26.jpg)
BWT–ProblemFormulaWon
AssumpWons:• Teamsize=P,Poolsize=N,(N≥P).• C(salary)isanN‐by‐1(column)vectorofposiWverealvalues
• RisanN‐by‐Kmatrixofrealvaluesintherange[0.0,1.0].Eachrowrepresentsaplayerinthepool.Eachcolumnrepresentsaskill
• B(totalquality)isa1‐by‐K(row)vectorofposiWverealvalues
Alltherelevantinfoisgiven.Thatis,{P,N,C,R,B}mustbesuppliedtous
Note:noguaranteethattheparametersaresetcorrectly
Note:cannothave‘half’aplayeronateam.Theplayeriseithersignedornot
4.26
![Page 27: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/27.jpg)
BWT–ProblemFormulaWon
Approach:1. Collectallparameters{P,N,C,R,B} %Input/loaddata2. Verifythatparametersaresetcorrectly %Errorchecking
3. StatetheprobleminmathemaWcalnotaWon:
• WeareclearlysolvingaconstrainedopWmizaWonproblem
• WearetryingtominimizealinearobjecWve(minimizethetotalsalary),subjectto:
• Oneequalityconstraint,ateamshouldhaveexactlyPplayers• Klinearinequalityconstraints(totalqualityforsomeskillisone
constraint,wehaveKskills)
• Ourvariablesmustbebinary{0,1},cannotsign‘half’aplayer
4. Output/verifythesoluWon %Output/savesoluWon
4.27
![Page 28: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/28.jpg)
OpWmizaWon
“Dothingsbestunderthegivencircumstances”
ApplicaWonsinalmosteveryfieldimaginable:planning,scheduling,resourceallocaWon,management,trafficcontrol
OpWmizaWonproblem:• Makeadecision
• Express/controlthequalityofthedecisionbytheobjecWvefuncWon
• TypicallyaminimizaWon/maximizaWontask
• Express“circumstances”thataffectthedecisionasconstraints
• Thetypeofopt.prob.isdeterminedbythenatureoftheobjecWvefuncWonandtheconstraints
4.28
![Page 29: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/29.jpg)
OpWmizaWon–GeneralForm
GeneralFrom:
minimize F(x) subjectto: gi(x)≤bi i=1,…,m
TheproblemischaracterizedbytheobjecWvefuncWonF(x),andtheconstraintsgi(x)
Thevariableorvectorx,belongstosomedomain/setSspecifiedbytheconstraints
LinearandQuadraWcprogramsarethemostfrequentproblemsyouarelikelytoencounter
4.29
![Page 30: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/30.jpg)
BWT–ProblemFormulaWon
MathemaWcalnotaWon:1. LetXbethevariable/soluWon(column)vector,X∈{0,1}N2. WewishtominimizetheobjecWvefuncWonCTX
3. Oneequalityconstraint:∑Xi=P
4. Klinearinequalityconstraints:RTX≥BT
5. Completeform:
minimize CTX subjectto: RTX≥BT 1TX=P
∀p,Xp∈{0,1}
4.30
![Page 31: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/31.jpg)
MATLABOpWmizaWonToolbox
Extensivepackage.ManyrouWnes,opWons.PlentyofdocumentaWon(‘help’isnotsufficient)• Firststep:defineyourproblemclearly,writedownyour
equaWons
• Secondstep:findtheappropriatesolver(whattypeofproblemareyousolving?)
• Thirdstep:convertyourproblemtosolverform.ThismightrequirecombiningequaWons,switchingsignofequaWons&objecWve,addingequaWons
• Fourthstep:setopWons,callsolver,examinethesoluWon
4.31
![Page 32: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/32.jpg)
MATLABOpWmizaWonToolbox
Findappropriatesolver:• hCp://www.mathworks.com/help/toolbox/opWm/ug/
bqnk0r0.html
• Frequentsolvers:linprog(),quadprog(),fmincon()
Solverformexample:• Linearprogram
€
minxf T x such that
A ⋅ x ≤ b,Aeq ⋅ x = beq,lb ≤ x ≤ ub
4.32
![Page 33: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/33.jpg)
BWT–ProblemFormulaWon
MATLABToolboxnotaWon:• Appropriatesolver:bintprog()• Why?SoluWonvectorisabinaryintegervector,objecWveislinear
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
4.33
![Page 34: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/34.jpg)
bintprog()
Convertedtosolverform,variables{f,A,b,Aeq,beq}
FuncWoncallopWons(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,opWons)x=bintprog(problem)[x,fval]=bintprog(...)[x,fval,exi�lag]=bintprog(...)[x,fval,exi�lag,output]=bintprog(...)
4.34
![Page 35: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/35.jpg)
bintprog()
Syntaxrules(forallsolvers):• Parameternotpassed,assumeitisempty• Parameterorderisimportant
• Toincludeasubsequentparameter,butomitaprecedingone,passanemptyarray[]
• ‘opWons’isastructspecifyingopWmizaWonmethoddetails.Ignoreit,unlessyouknowathingortwoaboutthefield
• Insteadofpassingmanyparameters,canpassasinglestruct‘problem’withappropriatefields
• OutputparametersincludesoluWon(x),valueofobjecWvefuncWonatthesoluWon(fval),flagindicaWngoutcomeofcall(exi�lag),anddetailsabouttheexecuWon(output)
4.35
![Page 36: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/36.jpg)
bintprog()–Examples
Parameternotpassed,assumeitisempty:• x=bintprog(f) %MinimizeobjecWvewithoutconstraints
Includesubsequentparameter,omitprecedingone:• x=bintprog(f,[],[],Aeq,beq) %Noinequalityconstraints
Passasinglestruct:1. problem.f=C;
2. problem.Aineq=‐R’;3. problem.solver=‘bintprog’;
4. x=bintprog(problem);
• NoWcethatfieldnamesareslightlydifferent
• Mustsetallfields(settoemptyifdoesn’texist)
4.36
![Page 37: COMS 3101 Programming Languages: MATLAB Lecture 4vovsha/coms3101/matlab/mlab_lec4.pdf · Next Lecture: Final project overview and opons Next ... should be squares in green. Adjust](https://reader034.vdocuments.mx/reader034/viewer/2022050506/5f97783e73514547af336cc6/html5/thumbnails/37.jpg)
bintprog()–Examples
Outputparameters: • ‘x’:thesoluWonvector• ‘exi�lag’:ifreturns1,problemsolvedsuccessfully
• ‘output’:astructurewithsoluWondetails.Forexample,output.WmeisexecuWonWme
• Cannameparametersinanywayyouwish
• [soln,fval,the_flag,soln_details]=binprog(problem)
• IfsoluWonvectorisnotwhatitshouldbe,youmustcheckalloutputparameterstodiscovertheproblem.Youshouldstartwiththe‘exi�lag’,thoughthereisnoprescribedapproachtodetectaproblem
4.37