matlab iii solving non-linear algebra problems justin dawber september 22, 2011

Download Matlab iiI Solving non-linear algebra problems Justin Dawber September 22, 2011

If you can't read please download the document

Upload: todd-underwood

Post on 26-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

  • Slide 1
  • Matlab iiI Solving non-linear algebra problems Justin Dawber September 22, 2011
  • Slide 2
  • Expectations/PreRequisites Introduction to MatLab I & II (or equal experience)Introduction to MatLab I & II (or equal experience) MatLab as a calculatorMatLab as a calculator Anonymous FunctionsAnonymous Functions Function and Script m-filesFunction and Script m-files MatLab BasicsMatLab Basics Element-wise OperationsElement-wise Operations 2-D and 3-D Plotting2-D and 3-D Plotting Code Cells and PublishingCode Cells and Publishing
  • Slide 3
  • Anonymous Function Review Used in calling functions indirectlyUsed in calling functions indirectly >> Sin = @sin; % The variable Sin points to the function sin >> Sin = @sin; % The variable Sin points to the function sin >> Sin(pi) % Evaluates the sine of pi>> Sin(pi) % Evaluates the sine of pi (Not the most useful example, more later)(Not the most useful example, more later) Can be used to create anonymous functionsCan be used to create anonymous functions >> myfun = @(x) 1./(x.3 + 3*x - 5)>> myfun = @(x) 1./(x.3 + 3*x - 5) >> myfun(3)>> myfun(3)
  • Slide 4
  • M-file review Scripts: No input and no output arguments. Contain a series of commands that may call other scripts and functionsScripts: No input and no output arguments. Contain a series of commands that may call other scripts and functions Functions: Accept input and returns output arguments. Usually called program routines and have a special definition syntax.Functions: Accept input and returns output arguments. Usually called program routines and have a special definition syntax. Code Cells: Defined breaks in code that will help breakdown solution processCode Cells: Defined breaks in code that will help breakdown solution process
  • Slide 5
  • What defines non-linear
  • Slide 6
  • HUMPS (Built-in) HUMPS is a built-in Matlab function that has a strong maxima at 0.3HUMPS is a built-in Matlab function that has a strong maxima at 0.3 For those that want to know:For those that want to know:
  • Slide 7
  • Introducing fsolve Solver for systems of non-linear equationsSolver for systems of non-linear equations Requires Optimization ToolboxRequires Optimization Toolbox Single Dimension SystemSingle Dimension System Use fsolve with an anonymous functionUse fsolve with an anonymous function Steps to a solutionSteps to a solution Define the Anonymous FunctionDefine the Anonymous Function Plot the function to visualize initial guessPlot the function to visualize initial guess Call fsolve with function and guessCall fsolve with function and guess solution = fsolve(@f, initial_guess)solution = fsolve(@f, initial_guess)
  • Slide 8
  • Lets See It! We will do the following:We will do the following: Review a script m-file in Matlab for HUMPSReview a script m-file in Matlab for HUMPS Start with a complete srciptStart with a complete srcipt Review Code cells to break-up the codeReview Code cells to break-up the code Plot the function to visualize the guessPlot the function to visualize the guess Iterate through the cellsIterate through the cells Review the initial guess and solutionsReview the initial guess and solutions Switch to MatLabSwitch to MatLab
  • Slide 9
  • An Example: Finding Equilibrium Concentrations For the reaction H2O + CO CO2 + H2For the reaction H2O + CO CO2 + H2 Given the Equilibrium constant, K = 1.44 Given the Equilibrium constant, K = 1.44 For an equimolar feed of H2O and CO, compute the equilibrium conversionFor an equimolar feed of H2O and CO, compute the equilibrium conversion SolutionSolution C_H2O = (C_H20) 0 * (1-Xe)C_H2O = (C_H20) 0 * (1-Xe) C_CO = (C_H20) 0 * (1-Xe)C_CO = (C_H20) 0 * (1-Xe) C_H2 = (C_H20) 0 * XeC_H2 = (C_H20) 0 * Xe C_CO2 = (C_H20) 0 * XeC_CO2 = (C_H20) 0 * Xe K = C_CO2*C_H2/(C_H20*C_CO)K = C_CO2*C_H2/(C_H20*C_CO)
  • Slide 10
  • Lets Try It: We will do the following:We will do the following: Write a script m-file in Matlab for the Equilibrium ConversionWrite a script m-file in Matlab for the Equilibrium Conversion Start with a skeleton scriptStart with a skeleton script Use Code cells to break-up the codeUse Code cells to break-up the code Plot the function to visualize the guessPlot the function to visualize the guess Review a common syntax problem for element-wise operationsReview a common syntax problem for element-wise operations Iterate through the cellsIterate through the cells Review the initial guess and solutionsReview the initial guess and solutions Switch to MatLabSwitch to MatLab
  • Slide 11
  • 2-Dimensional System of non-linear equations What do we have in this case?What do we have in this case? 2 surfaces2 surfaces What are we trying to find?What are we trying to find? The point in x and y where both surfaces are zeroThe point in x and y where both surfaces are zero What is different about this case?What is different about this case? Hard to visualizeHard to visualize Two initial guesses requiredTwo initial guesses required Requires a Function-Function m-fileRequires a Function-Function m-file Also know as sub-functions or function in a functionAlso know as sub-functions or function in a function
  • Slide 12
  • The multi-dimensional function m-file Use sub-functions (function-function)Use sub-functions (function-function) Primary function call fsolvePrimary function call fsolve Secondary or sub-function define the multi-variate systemSecondary or sub-function define the multi-variate system function main clear all; close all; clc; % We can make some plots to help identify initial guesses x = 0:0.1:2; y=x; [X,Y] = meshgrid(x,y); hold on surf(X,Y,2*X - Y - exp(X) + 2) % first function surf(X,Y,-X + 2*Y - exp(Y) + 2) % second function zlabel('z') view(69,8) % initial_guesses = [1.3 0.9]; [X,fval,exitflag] = fsolve(@myfunc,initial_guesses) function z = myfunc(X) % set of equations to be solved x = X(1); y = X(2); z = [2*x - y - exp(x) + 2; -x + 2*y - exp(y) + 2];
  • Slide 13
  • Lets see it: We will do the following:We will do the following: Review a script m-file in Matlab for two stretched HUMPS surfacesReview a script m-file in Matlab for two stretched HUMPS surfaces Start with the complete scriptStart with the complete script Review each of the Code cellsReview each of the Code cells Plot the function to visualize the guessPlot the function to visualize the guess Review the initial guessReview the initial guess Call fsolve and review solutionsCall fsolve and review solutions Switch to MatLabSwitch to MatLab
  • Slide 14
  • An example: 2-Dimensional system
  • Slide 15
  • Lets see it: We will do the following:We will do the following: Review a script m-file in Matlab for the preceding exampleReview a script m-file in Matlab for the preceding example Start with the complete scriptStart with the complete script Review each Code cellReview each Code cell Plot the functionPlot the function Review the initial guessReview the initial guess Call fsolve and review solutionsCall fsolve and review solutions Switch to MatLabSwitch to MatLab
  • Slide 16
  • n-Dimensional Systems Example fsolve also works for the n-dimensional casefsolve also works for the n-dimensional case No way to graph this caseNo way to graph this case Must have knowledge of the problem to specify and initial guessMust have knowledge of the problem to specify and initial guess Solve the set of equations:Solve the set of equations: 0 = K1-(yCO*yH2^3)/(yCH4*yH2O)*p^2;0 = K1-(yCO*yH2^3)/(yCH4*yH2O)*p^2; 0 = K2 - ((yCO^2)*(yH2^2))/(yCO2*yCH4);0 = K2 - ((yCO^2)*(yH2^2))/(yCO2*yCH4); 0 = (2*yCH4 + yH2 + yH2O)*n - nH2f;0 = (2*yCH4 + yH2 + yH2O)*n - nH2f; 0 = (0.5*yCO + yCO2 + 0.5*yH2O)*n - nO2f;0 = (0.5*yCO + yCO2 + 0.5*yH2O)*n - nO2f; 0 = (yCH4 + yCO + yCO2)*n - nCf;0 = (yCH4 + yCO + yCO2)*n - nCf; 0 = yCO + yCO2 + yCH4 + yH2 + yH2O - 1;0 = yCO + yCO2 + yCH4 + yH2 + yH2O - 1; GivenGiven K1 = 25.82;K1 = 25.82; K2 = 19.41;K2 = 19.41; p = 1;p = 1; nCf = 1; nH2f=0.5; nO2f = 0.5;nCf = 1; nH2f=0.5; nO2f = 0.5;
  • Slide 17
  • Lets see it: We will do the following:We will do the following: Review a script m-file in Matlab for the n-Dim exampleReview a script m-file in Matlab for the n-Dim example Start with the complete scriptStart with the complete script Review each Code cellReview each Code cell Cannot plot the functionCannot plot the function Postulate on the initial guessPostulate on the initial guess Call fsolve and review solutionsCall fsolve and review solutions Switch to MatLabSwitch to MatLab
  • Slide 18
  • Thing to consider when using fsolve No SolutionsNo Solutions Multiple SolutionsMultiple Solutions Depends on the initial guessDepends on the initial guess Infinite Solutions coincidenceInfinite Solutions coincidence The nature of Numerical Solvers Know your tolerancesThe nature of Numerical Solvers Know your tolerances Lets take a look at one of each:
  • Slide 19
  • No solution example Translated HUMPSTranslated HUMPS Lets slide the HUMPS graph up 50Lets slide the HUMPS graph up 50 It no longer crosses the X-axisIt no longer crosses the X-axis We can attempt to solve it in the same wayWe can attempt to solve it in the same way Lets see how fsolve handles it?Lets see how fsolve handles it?
  • Slide 20
  • Lets See it: We will do the following:We will do the following: Run the earlier script for the 1-D humps example with the graph translated +50Run the earlier script for the 1-D humps example with the graph translated +50 Start with the complete scriptStart with the complete script Run the scriptRun the script Confirm the translation of +50Confirm the translation of +50 Review the output from fsolveReview the output from fsolve Switch to MatLabSwitch to MatLab
  • Slide 21
  • Multiple Solution example Back to the earlier HUMPS exampleBack to the earlier HUMPS example Two different guesses yield two different solutionsTwo different guesses yield two different solutions As you can see, two Zeros. A guess around -.4 will return the lower zero, while a guess near 1.2 will yield the high one.As you can see, two Zeros. A guess around -.4 will return the lower zero, while a guess near 1.2 will yield the high one.
  • Slide 22
  • Infinite Solutions Example Back to a 2-D fsolve exampleBack to a 2-D fsolve example Solve the system of equations:Solve the system of equations: sin(x) + sin(y) - 1.5 sin(x) + sin(y) - 1.5 -sin(x) - sin(y) + 1.5 -sin(x) - sin(y) + 1.5
  • Slide 23
  • Lets See it: We will review the graph of the two surfaces in the preceding exampleWe will review the graph of the two surfaces in the preceding example View graph from different anglesView graph from different angles Call fsolve with multiple initial guessesCall fsolve with multiple initial guesses Switch to MatlabSwitch to Matlab
  • Slide 24
  • A little bit about Numerical Solvers - Tolerances Numerical Solvers search for a solution starting from and initial guessNumerical Solvers search for a solution starting from and initial guess Several search algorithms can be usedSeveral search algorithms can be used Termination criteriaTermination criteria Solver terminates when the value of the function is within a certain range close to 0Solver terminates when the value of the function is within a certain range close to 0 The solver is unaware of the scale of the problemThe solver is unaware of the scale of the problem If you are looking for a value in ml, but the problem is in m 3 the solver may stop at ~0.003 m 3 but this is 3 L!If you are looking for a value in ml, but the problem is in m 3 the solver may stop at ~0.003 m 3 but this is 3 L! Lets look at an example of this and how to correct itLets look at an example of this and how to correct it
  • Slide 25
  • Tolerance Concern Example
  • Slide 26
  • Tolerance Concern Example (cont.) How to Proceed?How to Proceed? Option One Change the toleranceOption One Change the tolerance OptimsetOptimset options = optimset('TolFun',1e-9);options = optimset('TolFun',1e-9); Be careful not to set tolerance too tight (1e-15 = too tight)Be careful not to set tolerance too tight (1e-15 = too tight) Then call fsolve with optionsThen call fsolve with options fsolve(f,cguess,options)fsolve(f,cguess,options) Results are now much more accurateResults are now much more accurate
  • Slide 27
  • Tolerance Concern Example (cont.) How to proceed?How to proceed? Option 2 - Scale the input units and guess:Option 2 - Scale the input units and guess: C A0 = 2 mol/LC A0 = 2 mol/L V = 10 LV = 10 L v =.5 L/sv =.5 L/s k =.23 L/mol/sk =.23 L/mol/s Guess =.5Guess =.5 Call fsolve with default tolerancesCall fsolve with default tolerances Results now more accurateResults now more accurate
  • Slide 28
  • Lets see it: We will do the following:We will do the following: Review a script m-file in Matlab for the preceding tolerance concern exampleReview a script m-file in Matlab for the preceding tolerance concern example Start with the complete scriptStart with the complete script Review each Code cellReview each Code cell Iterate through code cellsIterate through code cells Review solutions using different methodsReview solutions using different methods Switch to MatLabSwitch to MatLab
  • Slide 29
  • Polynomials in MATLAB Defining PolynomialsDefining Polynomials How to get f(x) = Ax 2 +Bx+C into MatLabHow to get f(x) = Ax 2 +Bx+C into MatLab Simple! --- >>f = [A B C]Simple! --- >>f = [A B C] Finding Roots of a polynomial fFinding Roots of a polynomial f Also Simple --- >>roots(f)Also Simple --- >>roots(f) An example: The Van Der Waal equation:An example: The Van Der Waal equation: V 3 ((pnb+nRT)/p)V 2 + (n 2 a/p)V n 3 ab/pV 3 ((pnb+nRT)/p)V 2 + (n 2 a/p)V n 3 ab/p Coefficients [1 -(pnb+nRT/p) (n 2 a/p) n 3 ab/p]Coefficients [1 -(pnb+nRT/p) (n 2 a/p) n 3 ab/p]
  • Slide 30
  • Lets try it: We will compare the solutions to the above polynomial using fsolve and rootsWe will compare the solutions to the above polynomial using fsolve and roots Start with a complete script m-fileStart with a complete script m-file Define Polynomial as Anonymous FunctionDefine Polynomial as Anonymous Function Define Polynomial as coefficient vectorDefine Polynomial as coefficient vector [a b c d][a b c d] Find solution using roots() and fsolve()Find solution using roots() and fsolve() roots is an analytical solutionroots is an analytical solution All solutionsAll solutions fsolve is a numerical solutionfsolve is a numerical solution Only the Closest SolutionOnly the Closest Solution Switch to MatlabSwitch to Matlab
  • Slide 31
  • Summary fsolve(@f,initial_guess) non-linear solver (From the optimization toolbox)fsolve(@f,initial_guess) non-linear solver (From the optimization toolbox) Remember to consider the no/multiple/infinite solution casesRemember to consider the no/multiple/infinite solution cases Remember to set your tolerances or scale you problem to ensure accuracyRemember to set your tolerances or scale you problem to ensure accuracy Especially important when using the units package (more on that later)Especially important when using the units package (more on that later) Provides only the solution closest to the initial guessProvides only the solution closest to the initial guess Quality of initial guess directly related to quality of solutionQuality of initial guess directly related to quality of solution Intuition about problem is beneficialIntuition about problem is beneficial Use graphical output to aid in choosing guessUse graphical output to aid in choosing guess Optimset can set various options for solveOptimset can set various options for solve >>help optimset for more info>>help optimset for more info roots() Solves polynomial defined by their coefficients.roots() Solves polynomial defined by their coefficients. Provides all solutionsProvides all solutions