Upload
gillian-peters
View
216
Download
0
Tags:
Embed Size (px)
Citation preview
Engineering Problem Engineering Problem Solving with ComputersSolving with Computers
MEPP Summer ResidencyAugust 2008
Outline for SessionOutline for SessionAbout meCourse overviewCasesExcel programming and
OptimizationMatlab Primer
IntroIntroJake Blanchard, Professor,
Engineering PhysicsPhD in Nuclear Engineering, UCLA,
1988Research: fusion technology, solid
mechanics, nuclear batteries for MEMS, laser effects in metals
Born and raised in Southern California
married with two kids (11 and 9 yrs)
My Research InterestsMy Research Interests
Fusion TechnologyFission Reactor Fuels
and StructuresNuclear
Microbatteries
Goal of EPSCGoal of EPSCStudents who have completed this
course should have a broad understanding of:◦Solution techniques for several equation
types◦Level of difficulty for various problem
types◦Appropriate tools for solving various
problems◦Advantages and disadvantages of using
computers to solve engineering problems
Goal of This SessionGoal of This SessionI just want to get you started with
the tools we use in my courseMy theory is that some exposure
now will benefit you in the SpringWe will repeat everything we do
today when the course starts, though in more depth
Therefore, don’t worry if you don’t catch on to everything right away
Approach Used in EPSCApproach Used in EPSCProblem-based using case
studiesAssigned and student-identified
projectsNo exams
TextbooksTextbooksWe will use a text I put together
from two full texts: one Excel-based and one Matlab-based ◦You won’t all need this and no
problems will be assigned from it◦Buy it from Rose
Many other background books are available if you need additional support
Numerical TopicsNumerical TopicsLinear and nonlinear equationsQuadratureOrdinary differential equations
◦initial value◦boundary value
OptimizationData AnalysisDatabases
Prerequisites and ResourcesPrerequisites and ResourcesMath skills: linear algebra
(matrices and vectors) and ordinary differential equations (first and second order)
Computer skills: some programming is useful, but not necessary
Used These Before?Used These Before?
FORTRANCC++PascalBasicJavaOthers?
• EES
• MathCAD
• Matlab
• Excel/Quattro
• Mathematica
• Maple
• Others?
ToolsToolsMicrosoft Excel (97, 2000, 2003,
etc.)Matlab from Mathworks
◦there is a student version for ~ $100◦Any version beyond Matlab 4 will work
fine, though a couple things got easier with version 6 and a few commands have changed
◦You can run it as “tethered” software from CAE if you are interested (www.cae.wisc.edu/tethered)
CasesCasesBroad coverage of engineering
disciplines and topicsThe more students can see
relevance of cases, the better
Case Titles and TopicsCase Titles and TopicsMacros in ExcelDatabases
◦Material Properties (choose your own for lesson)
Quadrature◦Automobile suspension
Roots◦natural frequencies of satellite boom
Linear Systems◦fluid flow network
Case Titles and TopicsCase Titles and Topics
Initial Value◦PSII target heating
Boundary Value◦chip cooling
Optimization (Linear Programming/Constraints)◦manufacturing
Case Titles and TopicsCase Titles and TopicsOptimization (Monte Carlo)
◦maximize profit with uncertain inputsCurve Fits
◦radioactive decay
Hands-On SessionHands-On SessionOptimization Problem in Excel
(using the Solver)Introduction to Matlab
First Download FilesFirst Download Fileshttp://www.cae.wisc.edu/~blanchar/
MEPP.html
Optimization of Water Optimization of Water DistributionDistributionConsider two bottling plants:
Mexico City and TepicConsider three customers: one in
Monterrey, one in Mazatlan, and the other in Acapulco
Question is: which plants should ship to which cities?
Plant DataPlant Data
Plant Production cost ($/gal)
Capacity
(Million gal/y)
Distance to
Acapulco (km)
Distance to
Monterrey (km)
Distance to
Mazatlan (km)
Mexico City
0.5 1 411 989 1085
Tepic 0.6 0.5 1064 1004 278
Customer DataCustomer Data
Customer Demand (Million gal/y)
Acapulco 0.32
Monterrey 0.44
Mazatlan 0.16
Best GuessBest GuessUse pencil and paper to make
best guess of optimum distribution
Goal is to meet demand with minimum cost
Selling price is the same in each city
Sheet SetupSheet Setup
What is total cost for your guess at the optimal distribution?
Using the SolverUsing the Solver
Tools/Add-Ins…SolverTools/Solver
Take a look at this link for further information:
http://econltsn.ilrt.bris.ac.uk/cheer/ch9_3/ch9_3p07.htm
The Main Solver WindowThe Main Solver Window
Dialog for Adding ConstraintsDialog for Adding Constraints
Results DialogResults Dialog
Your TaskYour TaskSet up the Solver, with all
appropriate constraints, to optimize this problem
Next ScenarioNext ScenarioWhat if the production cost in
Tepic drops to 0.45 $/gal?
Next ScenarioNext ScenarioWhat is optimum if demand
increases in each city by 50%? Put Tepic back at 0.6 $/gal on the production cost.
Adding a “Run” ButtonAdding a “Run” ButtonExcel has a built-in macro
language called Visual Basic for Applications (VBA)
It can be used to create user interfaces
We can use it to add a button for running the Solver
Using MacrosUsing MacrosMacros are written in a Basic-like
language called Visual Basic for Applications
Excel comes with a separate macro editor
To create or edit a macro, go to Tools/Macro/Visual Basic Editor
To add a new module go to Insert/Module
The MacroThe Macro
Sub runsolver() SolverSolveEnd Sub
Creating the ButtonCreating the ButtonGo to View/Toolbars/FormsFrom this Toolbar, click on the
button (row 2, column 2) and then trace out a button on a spreadsheet
Assign the “runsolver” macro to the button
Now click the buttonNote that you may have to add a
“Reference” to the Solver under Tools in the VBA Editor
User-Defined FunctionsUser-Defined FunctionsWe can also create user-defined
functions in VBAThese can be called from cells,
just like any built-in function
Creating a FunctionCreating a Function
Suppose we want to create an Excel function that takes a temperature in Celsius and converts to Fahrenheit
We would type the following in a module:
Function ctof(temp) ctof = 9 / 5 * temp + 32End Function
Using the functionUsing the functionThen you can go to the
spreadsheet and type =ctof(100)Or, you can put the value of
“100” into cell A1 and then type =ctof(A1) into some other cell
In fact, this function can be used just as any built-in Excel function can be used
ExerciseExerciseCopy this function and create
ftoc for converting from fahrenheit to celsius
The Macro LanguageThe Macro LanguageOperators: +, -, *, /, ^, ModComparison: =, <, >, <=, >=,
<>Logical Operators: And, Eqv,
Imp, Not, Or, XorIntrinsic Functions: Abs, Cos,
Sin, Tan, Atn (arc tangent), Exp, Log (natural), Sgn, Sqr (square root), Rnd (random number)
Flow ControlFlow Control
If condition Then statementsElse statementsEnd If
If x=0 Then f=1Else f=sin(x)/xEnd If
Flow ControlFlow Control
For counter=start To end statementsNext
For i=1 To 100 sum=sum+iNext
Flow ControlFlow Control
Do Until condition statementsLoop
i=1x=1Do Until i=50 x=x*i i=i+1Loop
Flow ControlFlow Control
Do While condition statementsLoop
i=1x=1Do While i<50 x=x*i i=i+1Loop
ExampleExampleWrite an Excel function that
calculates the factorial of some number Z
Factorial is Z*(Z-1)*(Z-2)*…*3*2*1
My solutionMy solution
Function fact(Z) x = 1 ans = 1 Do Until x = Z ans = ans * x x = x + 1 Loop fact = ansEnd Function
Another SolutionAnother Solution
Function fact(Z) ans = 1 For i = 1 To Z ans = ans * i Next fact = ansEnd Function
ExerciseExerciseWrite an Excel function that
calculates the sum of the first N cubes and test it
That is: 13+23+33+…+N3
What is the result for N=20?
MatlabMatlabMatlab began as a linear algebra
packageIt’s grown to be a general
purpose equation solverStrengths: robust routines,
excellent performanceWeaknesses: more difficult user
interface
Matlab DemosMatlab DemosType “demo”View:
◦Visualization/3D plots, vibration movie
◦Miscellaneous/Bending Truss
Matlab GUIsMatlab GUIs
Matlab has a tool for creating Graphical User Interfaces
You can start it up by typing guide at the command prompt
See an example by typing nextdemogui to run the file we downloaded earlier
Note that you may need to set the path by setting the Current Directory at the top of the command window
Matlab ToolkitsMatlab ToolkitsSimulink: dynamic systems
simulatorStateflow: event-driven systemsDSP, Signal Processing, Image
ProcessingControl, OptimizationPDE, Financial, Mappingand many more
Starting Out with MatlabStarting Out with MatlabStart Matlab - you’ll see the
“Command Window”Type the following:
A=[2 4; 1 3]
B=inv(A)
A*B
Plotting with MatlabPlotting with Matlab
list=0:0.1:20;y=sin(list);plot(list,y)
Using Scripts (m-files)Using Scripts (m-files)
Start up the editor (File/Open)Open test.mChange sin to cos in the scriptSaveGo back to command window and
execute by typing test
The scriptThe scriptclear allecho onA=[2 4; 1 3]B=inv(A)A*B%%Hit any key to continue
pauselist=0:0.1:20;y=sin(list);plot(list,y)
An ExampleAn ExampleSuppose we’re looking for a $100k,
30-year mortgage. What interest rate do I need to keep the payments below $700 per month?
Solve for i
0)1(
1)1(700100000
360
360
ii
i
ApproachApproachCreate user-defined functionPlot the functionFind point where function is 0
Create the functionCreate the function
function s=f(i)p=100000;n=360;a=700;s=p-a*((1+i).^n-1)./(i.*(1+i).^n);
Plot the FunctionPlot the FunctionFirst save file as f.mNow enter the following:
i=0.001:0.0001:0.01;y=f(i);plot(i,y)
ResultResultZero-crossing is around i=0.006Annual interest rate is 12*i, or
about 7%Try more accurate solution
12*fzero('f',0.006)
This gives about 7.5%
ExerciseExerciseWhat is the interest rate to keep
the payments below $700 for a 15 year mortgage?
Summary and ConclusionsSummary and ConclusionsGoal: broad understanding of
◦Solution techniques◦Level of difficulty◦Appropriate tools◦Advantages and disadvantages
Any comments, requests, or suggestions?
See You Next Spring!See You Next Spring!