Programming in Excel and MATLAB

advertisement
Programming
inExcelandMATLAB
CBE422
•  Example1:randomwalks
–  Excel:rand(),counBf,vlookup
–  MATLAB:forloops,ifstatements,ploFng
•  Example2:ParBclesonhexagonallaFce
•  Example3:MonteCarlointegraBon
Example,1:,random,walks,
•  Diffusion:,molecules,undergoing,random,walks,
•  Molecule,takes,n,steps,of,size,l,,each,in,a,random,
direcMon,,over,a,Mme,interval,t,
•  What,is,the,probability,density,,p(x,t),,of,observing,
a,molecule,between,x,and,x,+,dx*aUer,Mme,t?,
•  Answer'(1XD,case,,limit,of,large,n):,
p(x,t) =
⎛ x2 ⎞
1
exp ⎜ −
⎝ 4Dt ⎟⎠
4π Dt
nl 2
D=
2t
•  Objec,ve:,verify,this,through,simulaMon,of,1XD,
random,walks,
ExcelimplementaBon
•  UsemulBplesheets
•  RAND()producesuniformlydistributed
randomnumbers
•  VLOOKUP to select step to take based on
random number
•  FLOOR function to produce bin
corresponding to the final position
•  COUNTIF function to generate histogram
•  F9 to recalculate (produce new set of runs)
Matlab
•  MATLAB(MATtrixLABoratory)isapackageusedfortechnical
compuBng.ItintegratescomputaBon,visualizaBon,and
programming.
•  caninstallonyourownlaptop: hRp://www.princeton.edu/soTware/licenses/soTware/matlab/
• 
• 
• 
• 
• 
• 
• 
BasicMLelement:Matrices/Arrays
CasesensiBve(a≠A)
Implicittypeconversions(realsare“DoublePrecision,”64bit)
Semicolon(;)tosuppressprinBngofresults
Colon(:)toconstructarangeofvalues
Commentsareprecededby%
RelaBonaloperators:<,>,<=,>=,==,~=
Matlabwindows
Editor:towork
withscriptfiles
CommandWindow:
toenter
commandsand
data
Workspace:showsyouall“local”
variablesandtheirtypeandsize
Matlabsimplescripts
•  AKAm-files
•  Equivalenttotypingthecommandsone-byoneatthecommandprompt“>>”
•  Requirevariablestobedefinedwithinthe
scriptfile,orinteracBvelypriortoexecuBon
•  Allvariablescreatedinascriptfileremainin
workspaceaTerexecuBon
MatlabfuncBons
•  Takeargumentsandreturnoneormore
results
•  FirstresultisalsothevalueofthefuncBonif
usedinanassignmentstatement
•  Callis“ByValue”(argumentvaluesincalling
programarenotchangedevenifchanged
withinthefuncBon)
SimpleMatlabfuncBons
FuncBonarguments
CondiBonals
“For”loops
“While”loops
DebuggingMatlabfuncBons
•  Displayintermediateresultsbynotending
statementwith“;”
•  Cansetformal“breakpoints”and“condiBonal
breakpoints”incodeandpauseexecuBonto
examinevariables
Example2:parBclesonlaFce
Example3:MonteCarlointegraBon
Download