Answered step by step
Verified Expert Solution
Question
1 Approved Answer
function LAB04ex1 %NOTE: you CAN run this type of function m file as a script because it requires no inputs. Click the Green arrow above
function LAB04ex1 %NOTE: you CAN run this type of function m file as a script because it requires no inputs. Click the Green arrow above the "Run" tab t0 = 0; tf = 40; %initial and final time y0 = [-1; 0];%[y0, v0] [t,Y] = ode45(@f,[t0,tf],y0);%f=system of diff eqs; [t0,tf] y = Y(:,1); v = Y(:,2); %the output Y has 2 columns corresponding to y and v %the output Y has 2 columns corresponding to y and v figure(1); plot(t,y,'b-+'); %plots y(t) hold on plot(t,v,'ro-'); %plots v(t) legend('y(t)','v(t)') grid on; figure(2) plot(y,v); % plot solution in the space of y and v (instead of plotting y and v over time) axis square; %makes the figure window square xlabel('y'); ylabel('v'); ylim([-1.5,1.5]); xlim([-1,1]); grid on end %----------------------------------function dydt = f(t,Y) y = Y(1); v = Y(2);%for EX4 you will need a third element w=Y(3) dYdt = [v; cos(t)-4*v-3*y];%=[dy/dt; dv/dt], the two derivatives as a function of y and v end %% Lab 4 - Your Name - MAT 275 Lab % MATLAB solvers for First-Order IVP %% EX1 %A 6 PTS type LAB04ex1 LAB04ex1 %B 2PTS %do not print the entire vectors t and Y, but include a few values which %show where maxima occur %C 2 PTS %[ENTER COMMENTS. Each line must have % before it] %D 2 PTS %create a function file "LAB04ex1d" which is a duplicate of LAB04ex1 but with %the initial conditions for y and v changed. %figure(1) and figure(2) also need to be %changed to figure(3) and figure(4) (in order to plot part a and part d on separate figures). type LAB04ex1d LAB04ex1d %% EX2 %A 5 PTS %create a new mfile with the differential equation changed type LAB04ex2 %alternatively, you can paste in only the segment of the code that you modified %B 1 PTS %comments %C 1 PTS %comments %D 3 PTS %unfortunately, you may have to create yet another mfile, LAB04ex2d, in %order for the publishing to work in this case. %NOTE: there should only be ONE output plot for the code you write in %LAB04ex2d. The plot should superimpose solutions for y(t) from euler.m and %ode45. Include a legend to label each solution type LAB04ex2d LAB04ex2d %% EX 3 6 PTS %NOTE: the code for this part should be very similar to what you wrote for %EX1-A. You just need to modify the system of differential equations. % It's OK if you get the following error message: %"Warning: Failure at t=5.840631e+000. Unable to meet integration tolerances without %reducing the step size below the smallest value allowed (1.421085e-014) at time t type LAB04ex3 LAB04ex3 %Its fine if there is only be one outputted plot here (showing y(t) and v(t)) %% EX4 %A 6 PTS %NOTE: this code should also be very similar to what you wrote for %EX1-A and EX3 %when defining the function f at the bottom of your LAB04ex5.m file, dYdt %now needs to be a column with THREE elements. %LAB04ex5 should include commands which reproduce the plots shown in the %lab4 document type LAB04ex5 LAB04ex5 %B 2 PTS %short comment %C 2 PTS %differentiate each term of L4.7 with respect to time. You will need to use %the chain rule and product rule %D 2 PTS %Substitute the initial conditions of L4.8 into equation L4.7 at t=0, and %check that the equation is satisfied. You can write this as a comment. MATLAB sessions: Laboratory 4 MAT 275 Laboratory 4 MATLAB solvers for First-Order IVP In this laboratory session we will learn how to 1. Use MATLAB solvers for solving scalar IVP 2. Use MATLAB solvers for solving higher order ODEs and systems of ODES. First-Order Scalar IVP Consider the IVP \u001a y 0 = t y, y(0) = 1. (L4.1) The exact solution is y(t) = t 1 + 2et . A numerical solution can be obtained using various MATLAB solvers. The standard MATLAB ODE solver is ode45. The function ode45 implements 4/5th order Runge-Kutta method. Type help ode45 to learn more about it. Basic ode45 Usage The basic usage of ode45 requires a function (the right-hand side of the ODE), a time interval on which to solve the IVP, and an initial condition. For scalar first-order ODEs the function may often be specified using the inline MATLAB command. A complete MATLAB solution would read: 1 f = inline('t-y','t','y'); 2 [t,y] = ode45(f,[0,3],1); 3 plot(t,y) (line numbers are not part of the commands!) Line 1 defines the function f as a function of t and y, i.e., f (t, y) = t y. This is the right-hand side of the ODE (L4.1). Line 2 solves the IVP numerically using the ode45 solver. The first argument is the function f, the second one determines the time interval on which to solve the IVP in the form [initial time, final time], and the last one specifies the initial value of y. The output of ode45 consists of two arrays: an array t of discrete times at which the solution has been approximated, and an array y with the corresponding values of y. These values can be listed in the Command Window as [t,y] ans = 0 0.0502 0.1005 0.1507 0.2010 ........ 2.9010 2.9257 2.9505 2.9752 3.0000 1.0000 0.9522 0.9093 0.8709 0.8369 2.0109 2.0330 2.0551 2.0773 2.0996 c 2016 Stefania Tracogna, SoMSS, ASU 1 MATLAB sessions: Laboratory 4 Since the output is quite long we printed only some selected values. For example the approximate solution at t ' 2.9257 is y ' 2.0330. Unless specific values of y are needed it is better in practice to simply plot the solution to get a sense of the behavior of the solution. Line 3 thus plots y as a function of t in a figure window. The plot is shown in Figure L4a. 2.2 2 1.8 1.6 1.4 1.2 1 0.8 0.6 0 0.5 1 1.5 2 2.5 3 Figure L4a: Solution of (L4.1). Error Plot, Improving the Accuracy Error plots are commonly used to show the accuracy in the numerical solution. Here the error is the difference between the exact solution y(t) = t 1 + 2et and the numerical approximation obtained from ode45. Since this approximation is only given at specified time values (contained in the array t) we only evaluate this error at these values of t: err = t-1+2*exp(-t)-y err = 1.0e-005 * 0 0.0278 0.0407 0.0162 -0.0042 ...... -0.0329 -0.0321 -0.0313 -0.0305 -0.0298 (in practice the exact solution is unknown and this error is estimated, for example by comparing the solutions obtained by different methods). Again, since the error vector is quite long we printed only a few selected values. Note the 1.0e-005 at the top of the error column. This means that each component of the vector err is less than 105 in absolute value. A plot of err versus t is more revealing. To do this note that errors are usually small so it is best to use a logarithmic scale in the direction corresponding to err in the plot. To avoid problems with negative numbers we plot the absolute value of the error (values equal to 0, e.g. at the initial time, are not plotted): semilogy(t,abs(err)); grid on; c 2016 Stefania Tracogna, SoMSS, ASU 2 MATLAB sessions: Laboratory 4 5 10 6 10 7 10 8 10 0 0.5 1 1.5 2 2.5 3 Figure L4b: Error in the solution of (L4.1) computed by ode45. See Figure L4b. Note that the error level is about 106 . It is sometimes important to reset the default accuracy ode45 uses to determine the approximation. To do this use the MATLAB odeset command prior to calling ode45, and include the result in the list of arguments of ode45: f = inline('t-y','t','y'); options = odeset('RelTol',1e-10,'AbsTol',1e-10); [t,y] = ode45(f,[0,3],1,options); err = t-1+2*exp(-t)-y; semilogy(t,abs(err)) See Figure L4c. 10 10 11 10 12 10 13 10 14 10 15 10 16 10 0 0.5 1 1.5 2 2.5 3 Figure L4c: Error in the solution of (L4.1) computed by ode45 with a better accuracy. Parameter-Dependent ODE When the function defining the ODE is complicated, rather than entering it as inline, it is more convenient to enter it as a separate function file, included in the same file as the calling sequence of ode45 (as below) or saved in a separate m-file. In this Section we will look at an example where the ODE depends on a parameter. Consider the IVP \u001a 0 y = a (y et ) et , (L4.2) y(0) = 1. with exact solution y(t) = et (independent of the parameter a!). An implementation of the MATLAB solution in the interval [0, 3] follows. c 2016 Stefania Tracogna, SoMSS, ASU 3 MATLAB sessions: Laboratory 4 1 2 3 4 5 6 7 8 9 function ex_with_param t0 = 0; tf = 3; y0 = 1; a = 1; [t,y] = ode45(@f,[t0,tf],y0,,a); disp(['y(' num2str(t(end)) ') = ' num2str(y(end))]) disp(['length of y = ' num2str(length(y))]) %------------------------------------------------function dydt = f(t,y,a) dydt = -a*(y-exp(-t))-exp(-t); Line 1 must start with function, since the file contains at least two functions (a driver + a function). Line 2 sets the initial data and the final time. Line 3 sets a particular value for the parameter a. In line 4 the parameter is passed to ode45 as the 5th argument (the 4th argument is reserved for setting options such as the accuracy using odeset, see page 3, and the placeholder must be used if default options are used). Correspondingly the function f defined in lines 8-9 must include a 3rd argument corresponding to the value of the parameter. Note the @f in the argument of ode45. This is necessary when the function is not defined as inline. See the help on ode45 for more information. On line 5 the value of y(3) computed by ode45 is then displayed in a somewhat fancier form than the one obtained by simply entering y(end). The command num2string converts a number to a string so that it can be displayed by the disp command. The m-file ex with param.m is executed by entering ex with param at the MATLAB prompt. The output is >> ex_with_param y(3) = 0.049787 length of y = 45 The additional line 6 in the file lists the length of the array y computed by ode45. It is interesting to check the size of y obtained for larger values of a. For example for a = 1000 we obtain >> ex_with_param y(3) = 0.049792 length of y = 3621 This means that ode45 needed to take smaller step sizes to cover the same time interval compared to the case a = 1, even though the exact solution is the same! Not all problems with a common solution are the same! Some are easier to solve than others. When a is large the ODE in (L4.2) is said to be stiff. Stiffness has to do with how fast nearby solutions approach the solution of (L4.2), see Figure L4d. F Other MATLAB ODE solvers are designed to better handle stiff problems. For example replace ode45 with ode15s in ex with param.m (without changing anything else) and set a = 1000: 4 [t,y] = ode15s(@f,[t0,tf],y0,,a); >> ex_with_param y(3) = 0.049787 length of y = 18 c 2016 Stefania Tracogna, SoMSS, ASU 4 MATLAB sessions: Laboratory 4 Figure L4d: Direction field and sample solutions in the t-y window [0, 0.1] [0.9, 1] as obtained using DFIELD8: a = 1 (left) and a = 1000 (right). A solution exhibiting blow up in finite time Consider the Differential Equation dy = 1 + y2 , dt y(0) = 0 The exact solution of this IVP is y = tan t and the domain of validity is [0, 2 ). Let's see what happens when we try to implement this IVP using ode45 in the interval [0, 3]. >> f=inline('1+y^2','t','y'); >> [t,y]=ode45(f,[0,3],0); Warning: Failure at t=1.570781e+000. Unable to meet integration tolerances without reducing the step size below the smallest value allowed (3.552714e-015) at time t. > In ode45 at 371 The MATLAB ode solver gives a warning message when the value of t = 1.570781 is reached. This is extremely close to the value of /2 where the vertical asymptote is located. If we enter plot(t,y) we obtain Figure L4e on the left (note the scale on the y-axis), however, if we use xlim([0,1.5]), we can recognize the graph of y = tan t. 13 x 10 18 15 16 14 12 10 10 8 6 5 4 2 0 0 0 0.5 1 1.5 2 0 0.5 1 1.5 Figure L4e: Solution of y 0 = 1 + y 2 , y(0) = 0 without restrictions on the axis, and with xlim([0,1.5]) c 2016 Stefania Tracogna, SoMSS, ASU 5 MATLAB sessions: Laboratory 4 Higher-Order and Systems of IVPs We show here how to extend the use of ode45 to systems of first-order ODEs (the same holds for other solvers such as ode15s). Higher-order ODEs can first be transformed into a system of first-order ODEs to fit into this framework. We will see later how to do this. As an example consider the predator-prey system (Lotka-Volterra) representing the evolution of two populations. u1 = u1 (t) and u2 = u2 (t): du1 = au1 bu1 u2 , dt (L4.3) du2 = cu2 + du1 u2 dt with initial populations u1 (0) = 10 and u2 (0) = 60. The parameters a, b, c, and d are set to a = 0.8, b = 0.01, c = 0.6, and d = 0.1. The time unit depends on the type of populations considered. Although the ODE problem is now defined with two equations, the MATLAB implementation is very similar to the case of a single ODE, except that vectors must now be used to describe the unknown functions. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 function ex_with_2eqs t0 = 0; tf = 20; y0 = [10;60]; a = .8; b = .01; c = .6; d = .1; [t,y] = ode45(@f,[t0,tf],y0,,a,b,c,d); u1 = y(:,1); u2 = y(:,2); % y in output has 2 columns corresponding to u1 and u2 figure(1); subplot(2,1,1); plot(t,u1,'b-+'); ylabel('u1'); subplot(2,1,2); plot(t,u2,'ro-'); ylabel('u2'); figure(2) plot(u1,u2); axis square; xlabel('u_1'); ylabel('u_2'); % plot the phase plot %---------------------------------------------------------------------function dydt = f(t,y,a,b,c,d) u1 = y(1); u2 = y(2); dydt = [ a*u1-b*u1*u2 ; -c*u2+d*u1*u2 ]; In line 2 the 2 1 vector y0 defines the initial condition for both u1 and u2 . In line 4 the parameters are passed to the ODE solver ode45 as extra arguments (starting from the 5th ), as many as there are parameters in the problem (4 here). The output array y of ode45 now has 2 columns, corresponding to approximations for u1 and u2 , respectively, instead of a single one. In line 5 these quantities are therefore retrieved and stored in arrays u1 and u2, which are descriptive names. The part of the program defining the ODE system includes lines 11-14. Note that all the parameters appearing as arguments of ode45 must appear as arguments of the function f. For a specific value of t the input y to f is a 2 1 vector, whose coefficients are the values of u1 and u2 at time t. Rather than referring to y(1) and y(2) in the definition of the equations on line 14, it is best again to use variable names which are easier to identify, e.g., u1 and u2. Line 14 defines the right-hand sides of the ODE system as a 2 1 vector: the first coefficient is du2 1 the first right-hand side ( du dt ) and the second coefficient the second right-hand side ( dt ). Lines 6-10 correspond to the visualization of the results. To plot the time series of u1 and u2, we create a 2 1 array of subplots. Because the scales of u1 and u2 are different, it is best using two different graphs for u1 and u2 here. Type help subplot to learn more about it. On a different figure, we then plot the phase plot representing the evolution of u2 in terms of u1 . Note that u1 and u2 vary cyclically. The periodic evolution of the two populations becomes clear from the closed curve u2 vs. u1 in the phase plot. c 2016 Stefania Tracogna, SoMSS, ASU 6 MATLAB sessions: Laboratory 4 12 140 10 130 8 u1 120 6 110 4 100 2 5 10 15 20 u2 0 140 90 80 120 70 u2 100 60 80 50 60 40 40 0 5 10 15 20 2 4 6 8 10 12 u1 Figure L4f: Lotka-Volterra example. Reducing a Higher-Order ODE Numerical solution to IVPs involving higher order ODEs - homogeneous or not, linear or not, can be obtained using the same MATLAB commands as in the first-order by rewriting the ODE in the form of a system of first order ODEs. Let's start with an example. Consider the IVP d2 y dy +7 + 5y = sin t, dt2 dt with y(0) = 0.5, dy (0) = 0.5. dt To reduce the order of the ODE we introduce the intermediate unknown function v = dv dt 2 d y dt2 (L4.4) dy dt . As a result dv dt = so that the ODE can be written + 7v + 5y = sin t. This equation only involves first-order derivatives, but we now have two unknown functions y = y(t) and v = v(t) with two ODEs. For MATLAB implementations it is necessary to write these ODEs in the form d dt = . . .. Thus ( dy d2 y dy dt = v, +7 + 5y = sin t (L4.5) 2 dv dt dt = sin t 7v 5y. dt Initial conditions from (L4.4) must also be transformed into initial conditions for y and v. Simply, ( y(0) = 0.5, dy y(0) = 0.5, (0) = 0.5 (L4.6) dt v(0) = 0.5. EXERCISES Instructions: For your lab write-up follow the instructions of LAB 1. 1. (a) Modify the function ex with 2eqs to solve the IVP (L4.4) for 0 t 50 using the MATLAB routine ode45. Call the new function LAB04ex1. Let [t,Y] (note the upper case Y) be the output of ode45 and y and v the unknown functions. Use the following commands to define the ODE: function dYdt= f(t,Y) y=Y(1); v=Y(2); dYdt = [v; sin(t)-7*v-5*y]; Plot y(t) and v(t) in the same window (do not use subplot), and the phase plot showing v vs y in a separate window. Add a legend to the first plot. (Note: to display v(t) = y 0 (t), use 'v(t)=y''(t)'). Add a grid. Use the command ylim([-1.2,1.2]) to adjust the y-limits for both plots. Adjust the x-limits in the phase plot so as to reproduce the pictures in Figure L4g. Include the M-file in your report. c 2016 Stefania Tracogna, SoMSS, ASU 7 MATLAB sessions: Laboratory 4 y(t) v(t) 1 1 0.5 v=y' 0.5 0 -0.5 0 -0.5 -1 -1 0 5 10 15 20 25 30 35 40 45 50 -0.5 0 0.5 1 y Figure L4g: Time series y = y(t) and v = v(t) = y 0 (t) (left), and phase plot v = y 0 vs. y for (L4.4). (b) For what (approximate) value(s) of t does y reach a local maximum in the window 0 t 50? Check by reading the matrix Y and the vector t. Note that, because the M-file LAB04ex1.m is a function file, all the variables are local and thus not available on the Command Window. To read the matrix Y and the vector t, you need to modify the M-file by adding the line [t Y]. Do not include the whole output in your lab write-up. Include only the values necessary to answer the question. (c) What seems to be the long term behavior of y? (d) Modify the initial conditions to y(0) = 2, v(0) = 3 and run the file LAB04ex1.m with the modified initial conditions. Based on the new graphs, determine whether the long term behavior of the solution changes. Explain. Include the pictures with the modified initial conditions to support your answer. Nonlinear Problems Nonlinear problems do not present any additional difficulty from an implementation point of view (they may present new numerical challenges for integration routines like ode45). EXERCISES 2. (a) Consider the modified problem d2 y dy + 7y 2 + 5y = sin t, dt2 dt with y(0) = 0.5, dy (0) = 0.5. dt (L4.7) The ODE (L4.7) is very similar to (L4.4) except for the y 2 term in the left-hand side. Because of the factor y 2 the ODE (L4.7) is nonlinear, while (L4.4) is linear. There is however very little to change in the implementation of (L4.4) to solve (L4.7). In fact, the only thing that needs to be modified is the ODE definition. Modify the function defining the ODE in LAB04ex1.m. Call the revised file LAB04ex2.m. The new function M-file should reproduce the pictures in Fig L4h. Include in your report the changes you made to LAB04ex1.m to obtain LAB04ex2.m. (b) Compare the output of Figs L4g and L4h. Describe the changes in the behavior of the solution in the short term. (c) Compare the long term behavior of both problems (L4.4) and (L4.7), in particular the amplitude of oscillations. (d) Modify LAB04ex2.m so that it solves (L4.7) using Euler's method with N = 1000 in the interval 0 t 50 (use the file euler.m from LAB 3 to implement Euler's method; do not delete the lines that implement ode45). Let [te,Ye] be the output of euler, and note c 2016 Stefania Tracogna, SoMSS, ASU 8 MATLAB sessions: Laboratory 4 y(t) v(t) 1 1 0.5 v=y' 0.5 0 -0.5 0 -0.5 -1 -1 0 5 10 15 20 25 30 35 40 45 50 -0.5 0 0.5 1 y Figure L4h: Time series y = y(t) and v = v(t) = y 0 (t) (left), and phase plot v = y 0 vs. y for (L4.7). that Ye is a matrix with two columns from which the Euler's approximation to y(t) must be extracted. Plot the approximation to the solution y(t) computed by ode45 (in black) and the approximation computed by euler (in red) in the same window (you do not need to plot v(t) nor the phase plot). Are the solutions identical? Comment. What happens if we increase the value of N ? Include the modified M-file in your report. 3. Solve numerically the IVP d2 y dy + 7y + 5y = sin t, dt2 dt with y(0) = 0.5, dy (0) = 0.5 dt in the interval 0 t 50. Include the M-file in your report. Is the behavior of the solution significantly different from that of the solution of (L4.7)? Is MATLAB giving any warning message? Comment. A Third-Order Problem Consider the third-order IVP \u0012 \u00132 2 d3 y dy dy 2d y + 7y + 14y +5 = cos t, 3 2 dt dt dt dt Introducing v = v(0) = dy dt (0) dy dt and w = dy 2 dt2 we obtain 2 dv dt with y(0) = 0.5, = w and dw dt = d3 y dt3 dy d2 y (0) = 0.5, 2 (0) = 1.625. (L4.8) dt dt = cos t 7y 2 w 14yv 2 5v. Moreover, = 0.5 and w(0) = ddt2y (0) = 1.625. Thus (L4.8) is equivalent to dy y(0) = 0.5, = v, dt dv v(0) = 0.5, with dt = w, dw 2 2 w(0) = 1.625. dt = cos t 7y w 14yv 5v (L4.9) 4. (a) Write a function M-file that implements (L4.8) in the interval 0 t 50. Note that the initial condition must now be in the form [y0,v0,w0] and the matrix Y, output of ode45, has now three columns (from which y, v and w must be extracted). On the same figure, plot the three time series and, on a separate window, plot the phase plot using figure(2); plot3(y,v,w,'k.-'); grid on; view([-40,60]) xlabel('y'); ylabel('v=y'''); zlabel('w=y'''''); c 2016 Stefania Tracogna, SoMSS, ASU 9 MATLAB sessions: Laboratory 4 y(t) v(t) w(t) 1 0.5 2 0 w=y'' 0 -2 -4 1.5 -0.5 0.6 1 0.4 0.5 0.2 0 0 -1 v=y' 0 5 10 15 20 25 30 35 40 45 -0.2 -0.5 50 -0.4 -1 y -0.6 Figure L4i: Time series y = y(t), v = v(t) = y 0 (t), and w = w(t) = y 0 (t) (left), and 3D phase plot v = y 0 vs. y vs w = y 00 for (L4.8) (rotated with view = [-40,60]). Do not forget to modify the function defining the ODE. The output is shown in Fig. L4i. The limits in the vertical axis of the plot on the left were deliberately set to the same ones as in Fig. L4h for comparison purposes using the MATLAB command ylim([-1.2,1.2]). Include the M-file in you report. (b) Compare the output of Figs L4h and L4i. What do you notice? (c) Differentiate the ODE in (L4.7) and compare to the ODE in (L4.8). (d) Explain why the solution of (L4.7) also satisfies the initial conditions in (L4.8). Hint: Substitute t = 0 into (L4.7) and use the initial conditions for y and v. c 2016 Stefania Tracogna, SoMSS, ASU 10 raulbehl@gmail.com raulbehl at gmail dot com
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started