lab 10

pdf

School

San Jose State University *

*We aren’t endorsed by this school

Course

130

Subject

Mechanical Engineering

Date

Feb 20, 2024

Type

pdf

Pages

11

Uploaded by PrivateRook16679

Report
Lab 10: Solving Nonlinear Equations |l © Matthew Leineweber, PhD BME 130 - Numerical Methods in Biomedical Engineering San Jose State University Instructor:Prof. Abdulmelik Mohammed Lab TA: Nihar Prakash, Ammar Babiker By: Philippe Moffet, Lab Group #: 03, Year: Fall 2023 Table of Contents Introduction Anonymous Functions Activity 1 Activity 2 Newton Raphson Method Activity 3 Activity 4 Using MATLAB's fzero to Solve Nonlinear Equations Activity 5 Activity 6 Using fsolve Activity 7 Post Lab References and Documentation Function Definitions Newton Raphson Function (to be completed by student) Introduction So far we have been exploring “bracketing methods” for solving nonlinear equations, namely the method of False Position (a.k.a Interpolation) and the Bisection method. These techniques are so called because they converge on a solution by successively iterating a pair of boundary points that lie on either side of the root until the range between the boundaries is negligibly small. Of these two methods, the False Position technique will typically converge faster than the Bisection method for functions with steep slopes near the root, but may take significantly longer if the slope is very shallow. We also saw how we can use function handles to pass functions as input arguments into other functions. This capability becomes extremely useful trying to iteratively solve equations, since it allows us to write a single solver function (e.g. FalsePosition2) to be used with any expression to be solved. However, defining standalone function files or sub-functions can be somewhat cumbersome when all our function needs to do is evaluate a single mathematical expression. Luckily, MATLAB allows us to define anonymous functions that can streamline this process allow us to define simple functions on the fly.
In today’s lab we will build off the foundation we laid last week to introduce a new technique for solving nonlinear equations, and show how we can use anonymous functions to simplify the solving process. This new solver, the Newton Raphson method, will often converge much faster than our previous methods (i.e. require fewer iterations). We will also explore how we can use some of MATLAB'’s pre-built functions to solve equations as well. Anonymous Functions We've already seen how writing functions and sub-functions makes our lives much easier by removing the need to customize every section of code to tailor a specific problem. However, if we only want our function to perform one or two steps, such as evaluating the result of a mathematical expression, writing an entire function m-file or sub-function can be tedious a little cumbersome. Enter the anonymous function. Anonymous functions can accept inputs and return outputs, like a regular function, but they contain only one or two executable lines of code, and can be defined at the command line, in a script, or within another user-defined function. These special functions are defined with the format: fun = @(inputArguments) expr Here, fun is the name of the anonymous function, inputArguments is the list of input arguments, and expr is the single line of code (expression) for the function. In this anonymous function definition, the ‘@ symbol tells MATLAB that fun will be a function with input variable: inputArguments. You may recognize the use of the ‘@ symbol from our discussion of function handles last week. Anonymous functions basically combine a function definition and a function handle into a single statement. For example, if we were to write an anonymous function that takes an input xand returns its cube, x3, we would write: cube = @ (x) x"3 cube = function_handle with value: @(x)x"3 Once an anonymous function is defined, it can be used to evaluate the function when the input variable is assigned a specific value: cube(2) ans = 8 Which is just the value evaluated at x = 3. As shown above, to call (use) an anonymous function, simply type the name of the anonymous function, followed by the value for the input variable in parentheses. If you wish to assign an array to the input variable rather than a single scalar value, you must first define the anonymous function with element-by-element powers instead: n = I1x3
cube = @ (x) x.”3 cube = function _handle with value: @(x)x.”"3 cube(n) ans = 1x3 1 8 27 Activity 1 Define an anonymous function to perform the following calculation f(x) = X +2x+2— 10&3_2’(2 Then use the function to evaluate f(x) for x=5 andfor x=[-1 4 9] % Define the anonymous function x=@(x)x."3+(2*x)+2- (10*exp(-2*x.72)) fx = function_handle with value: @(x)x."3+(2*x)+2-(10*exp(-2*x."2)) Run the function to perform the calculation on the following inputs % Define the x-values to be tested X1l = 5; xr = [-1 4 9]; Assign the result of f(x) to variables f1 and f2, respectively. % Evaluate fx1 = f(x1) and fx2 = f(x2) f1 = fx(x1) f1 = 137 2 = fx(xr) f2 = 1x3 -2.3534 74.0000 749.0000 So far we have explored anonymous functions with only one input variable, however, it's possible to have several input variables (e.g. x, y, z, etc.). To write an anonymous function for the Pythagorean Theorem, which we’ll call hypotenuse, we would have two input variables, a and b, representing the lengths of the sides of a right triangle, and the output will be the length of the hypotenuse. hypotenuse = @ (a,b) sqrt(a”2+b”2) hypotenuse = function handle with value: @(a,b)sgrt(a*2+b”2)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
To use multiple input variables in an anonymous function, just separate them by commas in parentheses after the “@”. Let’s evaluate the function for ¢ = 3 and » = 4: hypotenuse(3,4) ans = 5 What if you would like to evaluate several values in a multivariable function? The first step, just like with single variable functions, is to define the anonymous function element-by-element: hypotenuse = @ (a,b) sqrt(a.”2+b.”2) hypotenuse = function_handle with value: @(a,b)sgrt(a.”2+b.”2) Now, let’s find the hypotenuse length for two different triangles, one with sides length 5 and 12, and the other with sides length 7 and 24 hypotenuse([5,7],[12,24]) ans = 1x2 13 25 Where 13 is the output corresponding to the |5, 7] input, and 25 is the output corresponding to the [12,24] input. You'll notice that square brackets were used for each of the two input variables, a and b. It looks confusing that terms from different triangles are grouped together, but in order for MATLAB to compute the function as desired, this format is necessary. Note, that the previous line of code is equivalent to the following set of commands: A= [5,7]; B [12,24]; hypotenuse(A,B) ans = 1x2 13 25 You can also use pre-defined variables in an anonymous function’s mathematical expression, but note that if you assign new values to variables used in your anonymous function, the original values will still be used unless you redefine your anonymous function. Activity 2 Let’s illustrate this last point using the code below. Before running the code, write down what you think the values for output? and output2 should be. % Define Variables 'a' and 'b': a = 3; b = 4; % Define the anonymous function fun = @(x,y) a*x + b*y;
% Use the fun function to operate on 'a' and 'b' outputl = fun(1,2); % Define new values of 'a' and 'b’ a = 2; b = 2; % Use the fun function again output2 = fun(1,2); Expected Output: 3*2+4*2 2*1+2*2 Now let's look at the actual code % Define Variables 'a' and 'b': a = 3; b = 4; % Define the anonymous function fun = @(x,y) a*x + b*y; % Use the fun function to operate on 'a' and 'b' outputl = fun(1,2) outputl = 11 % Define new values of 'a' and 'b’ a = 2; b = 2; % Use the fun function again output2 = fun(1,2) output2 = 11 Are the values for outputl and output2 what you expected? Why are they the same? Answer: No, they were both the same answer, because you cannot redefine on a called function. Finally, like function handles, anonymous functions can be directly passed into other functions as arguments. This capability makes anonymous functions particularly well-suited for defining simple mathematical expressions without needing to create a fully-defined sub-function (like the Eqn function in Activities 3,4, and 5in Lab 9). Newton Raphson Method Like our other two methods discussed last week, the Newton Raphson method requires us to first select a tolerance ¢, that will define our stopping criterion. However, rather than selecting an initial range, this method only requires a single point to be selected. This initial guess, usually denoted as x( represents our first approximation of the actual root. As the method proceeds, this initial guess is updated (x;— x> —...— x,) at each iteration.
The Newton Raphson is similar to the False Position method in that it uses a line drawn from a point on our function f(x) to guide us towards the true root. However, instead of defining the line between two points straddling the x-axis, the Newton Raphson method uses a line tangent to the function at our current point, x,, . Recalling that the slope of the tangent line to f(x,) is defined by its derivative f'(x,), then the equation of the tangent line is y— fxn) = fxn){x xn) Therefore, if we want to find the point x,,.; where this line crosses the x-axis, then we set y = (0 and rearrange our equation: 0—flam) = [ xn)Xnt1 Xn) J(xn) Xn —7 f (Xn) Now this new point x,,; becomes our new approximation of the root. Our error equation remains the same: Xn+1 Eq But plugging in our definitions for x°* = x, and x™" = x,,; we can simplify the expression: | f(xn)) Id [ | Xn | xn P e/ B B =( f () =‘_ foa) || f) i | X1 Xn+1 J (Xn)Xn+1 f n)Xn+1 Note that the Newton Raphson method does not require us to check any intervals to ensure that they straddle the x-axis, as this method allows us to directly approximate the root at each iteration. However, unlike the False Position method, this technique is not guaranteed to converge for all initial guesses (See Chapra 6.2.2 for cases where Newton Raphson will not work). Furthermore, prior to using the Newton Raphson method, we need to have an analytical expression for both the equation to be solved f(x) and its first derivative f'(x)! Activity 3 We are now ready to write our own function to perform the Newton Raphson method. This function is going to need four inputs: 1. An expression for the function f(x) to be solved 2. An expression for the derivative f'(x) 3. The initial guess x 4. The desired tolerance 1ol Similar to our FalsePosition2 function from Lab 9, we will want two outputs: 1. The solution root xr 2. The full iteration history iterTable Using the outline contained in the NewtonRaphson function at the end of this live script , complete the function to calculate the roots of a user-defined equation using the Newton Raphson method.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Test your newly written function to solve x> 4 = () with a maximum acceptable relative error of ler| = 0.0005 % Define fx as an anonymous function containing the equation to be solved fx = @(x) x*2-4; % Define dfx as the derivative of fx dfx = @(x) 2*x; % Define the initial guess X0 = 1; % Define the tolerance tol = 0.0005; % Call the NewtonRaphson function [xr,iterTable] = NewtonRaphson(fx,dfx,x0,tol) Xr = 2.0000 iterTable = 5x5 1.0000 -3.0000 2.0000 2.5000 1.5000 2.5000 2.2500 5.0000 2.0500 0.4500 2.0500 0.2025 4.1000 2.0006 0.0494 2.0006 0.0024 4.0012 2.0000 0.0006 2.0000 0.0000 4.0000 2.0000 0.0000 Activity 4 Let’s write a short script to evaluate the roots of the function f(x) = v/x = (Inx)’ Right away we know that we are going to have to evaluate the derivative f'(x) analytically before proceeding. Rewriting our expression for f(x) as f(x) =x" (Inx)* Helps make it clear that 21Inx X f(x)=05x"" - Using our basic structure from our scripts from last week, along with our newfound knowledge of anonymous functions we can select our initial guess from a plot of the function % Define an anonymous function fx that contains the expression to be solved fx = @(x)x.~(-.5)-(log(x))."2 fx = function_handle with value: @(x)x.”(-.5)-(log(x))."2 % Define an anonymous function fxPrime that contains the derivative of the % expression to be solved fxPrime = @(x) -0.5 * x.~(-1.5) - 2*log(x) ./ X; % Define vector x to represent the independent variable
X = linspace(90,10,100); % Define vector y to represent the dependent variable y(x) y = fx(x); % PLOT fig = figure; plot(x,y, 'linewidth',1.5); grid; xlabel('x"); ylabel('y'); title('Activity 4"); ax = gca; ax.FontSize = 11; ax.XAxislLocation = ‘origin’; % Select initial point X0 = 3.5; % Select initial point % Show initial point on the graph fxn = fx(x0); hold on; plot(x@,fxn, 'ro’, 'linewidth"',1.5); Activity 4 Now that our initial value has been selected, we just need to define our tolerance, and then we are all set to begin finding our root with our NewfonRaphson.mfunction.
tol = 0.001; % 0.1% Error % FIND ROOT using NewtonRaphson [Xxr, iterTable] = NewtonRaphson(fx, fxPrime, x0, tol) Xr = 2.2604 iterTable = 3x5 3.5000 -1.0349 -0.7922 2.1937 1.3063 2.1937 0.0580 -0.8701 2.2604 0.0667 2.2604 0.0000 -0.8687 2.2604 0.0000 Using MATLAB’s fzero to Solve Nonlinear Equations MATLAB has a built-in nonlinear equation solver, called fzero[2], that can also be used to solve nonlinear equations. This function uses a combination of Bisection, Secant (similar to Newton Raphson), and inverse quadratic interpolation algorithms to solve the desired equation. Like our NewtonRaphson function from Activity 3, fzero requires a function handle (containing the equation to be solved) fun and initial guess x0 as inputs, and returns the root as its output: x = fzero(fun,x0); Note that whatever function you use, it can only have ONE VARIABLE as an input argument! It is also important to know that the function to be solved must cross the -axis. Activity 5 Let’'s do an example. Suppose we wanted to calculate the roots of the equation (x 4)> = 16. We can first define an anonymous function to represent the rearranged expression (x —4)> 16 =0 Notice how must set up the equation in the form f(x) = 0! fun = @(x) (x-4)"2 - 16 fun = function_handle with value: @(x)(x-4)"2-16 Then we can use our solver: fzero(fun,9) X | X = 8 Verify the MATLAB output by analytically solving the expression. (x—4)* = 16 x—4 = 4 x = 8 Answer: Matlab did infact solve the express, both have answer of 8. Activity 6 Try using fzero to find the roots to the polynomial f(x) = x*. What does MATLAB return as the solution? Why?
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
% Assign values of x fx Xpr @(x) x."2; fzero(fx,1) Exiting fzero: aborting search for an interval containing a sign change because NaN or Inf function value encountered during search. (Function value at -1.7162e+154 is Inf.) Check function or try again with a different starting value. xr = NaN Answer: Since the solution to x> = 0 does not actually cross the x-axis (it simply touches the x-axis and then starts going positive again), solutions like Newton Raphson and bracketing methods will not converge. Using fsolve In addition to fzero, MATLAB can also solve nonlinear equations using the fsolve [3] function (if you have access to the Optimization Toolbox). If you are using the basic student license ($50 version) and do not have access to the Optimization Toolbox, you should delete Activity 7) X = fsolve(fun,x0) Similar to the fzero command, is the solution, or zero of the function, fun is the name of the function to be solved, and x@ is the x-value where the function touches the x-axis (does not have to cross it). Using fsolve is much more robust than using fzero since it will be able to locate a function’s roots regardless of whether it crosses the x-axis or not. Typically, fzero is meant to solve systems of nonlinear equations (rather than just a single equation) where more than one variable must be found, and therefore uses (more sophisticated) algorithms specifically designed for that purpose. However, it can still work to solve single equations. Activity 7 Now use fsolve to solve f(x) = x*. Did it work? xr = fsolve(fx,1) ‘fsolve' requires Optimization Toolbox. Answer: No, it says it requires an optimization toolbox. Post Lab Complete the Lab 10 Post Lab Assignment on MATLAB Grader References and Documentation [1] https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html [2] https://lwww.mathworks.com/help/matlab/ref/fzero.html [3] https://www.mathworks.com/help/optim/ug/fsolve.html Function Definitions
Newton Raphson Function (to be completed by student) function [xr,iterTable] = NewtonRaphson(fx,dfx,x1,tol) %NEWTONRAPHSON Performs Newton Raphson method to solve function fx given %starting guess x1 % fx = function handle of equation to solve % dfx = derivative of function % x1 = starting guess % tol = desired tolerance (24 o % Estimate initial error err = tol+l; % Initialize the counter counter = 1; % Perform the Newton Raphson Method while err > tol % Define the new root approximation, x2 xr = x1 - fx(x1)/dfx(x1); % Update the error err = abs(xr - x1); % Update the iteration table iterTable(counter,:) = [x1 fx(x1) dfx(x1l) xr err]; % Update the counter counter=counter+1l; % Replace the old guess with the new guess X1l = Xr; end end