Ordinary Differential Equations (Ode) Solving Using Matlab

  • Upload
    ali

  • View
    240

  • Download
    0

Embed Size (px)

Citation preview

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    1/51

    Aboozar Ghaffari

    Engineering Mathematics Course:Solving 

    Ordinary Differential Equations

    Using MATLAB®

    University of Tabriz, Department of mechatronic

    In the name of GOD

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    2/51

     حضرت

     سوگواری

     ايام

     تسليت

     عرض

     با

    ابا عبداهللا الحسين

    و عروج مل وتی حضرت 

    منتظری

     عظمی

     اهللا

     آيت

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    3/51

    A first order ordinary differential equation has the formx’ = f (t,x).

    To solve this equation we must find a function x(t) such thatx‘(t) = f (t, x(t )), for all t .

    This means that at every point (t, x(t)) on the graph of x, the graph must haveslope equal to f (t,x(t)).

    We can turn this interpretation around to give a geometric view of whata differential equation is, and what it means to solve the equation.

    Imagine, if you can, a small line segment attached to each point (t, x)with slope  f (t,x).

    This collection of lines is called a direction line field, and it provides the geometric interpretation of a differential equation.

    To find a solution we must find a curve in the plane which is tangent ateach point to the direction line at that point.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    4/51

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    5/51

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    6/51

    Appendix: Downloading and Installing the Software Used in This Manual The MATLAB programs dfield, pplane, and odesolve, and the solvers eul, rk2, and rk4 described in this manual

    are not distributed with MATLAB. They are MATLAB function M-files and are available for download over theinternet.

    However, odesolve is new, and only works with MATLAB ver 6.0 and later. The solvers are the same for allversions of MATLAB.

    The following three step procedure will insure a correct installation, but the only important point is that the filesmust be saved as MATLAB M-files in a directory on the MATLAB path.

    • Create a new directory with the name odetools (or choose a name of your own). It can be located

    anywhere on your directory tree, but put it somewhere where you can find it later.

    • In your browser, go to http://math.rice.edu/~dfield/. For each file you wish to download,

    click on the link. In Internet Explorer, you are given the option to save the file.. In either

    case, save the file with the subscript .m in the directory odetools.

    • Open the path tool by executing the command pathtool in the MATLAB command window, or by

    selecting File→Set Path .... Follow the instructions for adding the directory odetools to the path.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    7/51

    Euler’s Method

    We want to find an approximate solution to the initial valueproblem y’ = f (t,y), with y(a) = y0,on the interval [a,b].

    In Euler’s very geometric method, we go along the tangent line tothe graph of the solution to find the next approximation.

    We start by setting t0 = a and choosing a step size h. Then we inductively define

     yk+1 = yk + h*f (tk, yk),

    tk+1 = tk + h,

    for k = 0, 1, 2, . . . , N, where N is large enough so that tN ≥ b.

    This algorithm is available in the MATLAB command eul.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    8/51

    Example 1. Use Euler’s method to plot the

    solution of the initial value problem

     y’ = y + t, y(0) = 1 (5.2) on the interval [0, 3] .

    Note that the differential equation in (5.2) is in normal form y’ = f (t,y), where f ‘(t,y) = y + t .

    Before invoking the eul routine, you must first write afunction M-file

    function yprime = yplust(t,y)

    yprime = y + t;

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    9/51

    >> yplust(1,2)ans = 3

    Now that your function M-file is operational, it’s time to invokethe eul routine. The general syntax is[t,y]=eul(@yplust,tspan,y0,stepsize)

    where yplust is the name of the function M-file, tspan is the vector[t0,tfinal] containing the initial and final time conditions, y0 is they-value of the initial condition, and stepsize is the step size to beused in Euler’s method.

    Actually, the step size is an optional parameter. If you enter thisprogram will choose a default step size equal to (tfinal-t0)/100.

    [t,y]=eul(@yplust,tspan,y0)

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    10/51

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    11/51

    Note how the error decreases, but the

    computation time increases as you

    reduce the step size.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    12/51

    log10(maximum error) = A + B log10(step size),

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    13/51

    The Second Order Runge-Kutta Method

    What is needed are solution routines that will provide moreaccuracy without having to drastically reduce the step sizeand therefore increase the computation time.

    The Runge-Kutta routines are designed to do just that. The

    simplest of these, the Runge-Kutta method of order two, issometimes called the improved Euler’s method.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    14/51

    Again, we want to find a approximate solution of the initialvalue problem y’ = f (t,y), with y(a) = y0, on the interval [a, b].

     As before, we set t0 = a, choose a step size h, and then inductivelydefine

    s1 = f (tk, yk),s2 = f (tk + h, yk + hs1),

     yk+1 = yk + h(s1 + s2)/2,

    tk+1 = tk + h,

    for k = 0, 1, 2, . . . , N, where N is large enough so that tN ≥ b. This algorithm is available in the M-file rk2.m, which is listed in

    the appendix of this chapter.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    15/51

    The syntax for using rk2 is exactly the same as the syntaxused for eul.

    As the name indicates, it is a second order method, so, if yk isthe calculate approximation at tk, and y(tk) is the exact solution

    evaluated at tk, then there is a constant C such that

    | y(tk) − yk| ≤ C|h|^2, for all k.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    16/51

    The Fourth Order Runge-Kutta Method

    This is the final method we want to consider. We want to find an approximate solution to the initial value problem  y

    = f (t,y), with y(a) = y0, on the interval [a, b].

    We set t0 = a and choose a step size h. Then we inductively define

    for k = 0,

    s1 = f (tk, yk),s2 = f (tk + h/2, yk + hs1/2),

    s3 = f (tk + h/2, yk + hs2/2),

    s4 = f (tk + h, yk + hs3),

     yk+1 = yk + h(s1 + 2s2 + 2s3 + s4)/6,

    tk+1 = tk + h,

    1, 2, . . . , N, where N is large enough so that tN ≥ b. This algorithm is availablein the M-file rk4.m, which is listed in the appendix of this chapter.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    17/51

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    18/51

    Introduction to PPLANE7

    A planar system is a system of differential equations of the formx’ =f (t, x, y),

     y’ =g(t, x, y). (7.1)

    The variable t in system (7.1) usually represents time and is called

    the independent variable. Frequently, the right-hand sides of the differential equations do

    not explicitly involve the variable t , and can be written in theform

    x’ = f (x, y), y’ = g(x, y). (7.2)

    Such a system is called autonomous.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    19/51

    System (7.1) can be written as the vector equation

    If we let x’ = [x,y]’ , then x’ = [x’,y’]’ and equation (7.4)becomes

    x’ = F(t, x).

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    20/51

    MATLAB’s built-in numerical solvers

    This is one of the most important chapters in this manual. Herewe will describe how to use

    MATLAB’s built-in numerical solvers to find approximatesolutions to almost any system of differential equations. At thispoint readers might be thinking, “I’ve got dfield6 and pplane6 andI’m all set.

    I don’t need to know anything further about numerical solvers.”Unfortunately, this would be far from the truth.

    For example, how would we handle a system modeling a driven,

    damped oscillator such as X1’ = x2,

    x2 ‘= −2x1 − 3x2 + cos t.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    21/51

    A new suite of ODE solvers was introduced with version 5 ofMATLAB.

    The suite now contains the seven solvers ode23, ode45,ode113, ode15s, ode23s, ode23t, and ode23tb.

    We will spend most of our time discussing the generalpurpose solver ode45. We will also briefly discuss ode15s, anexcellent solver for stiff systems.

    Although we will not discuss the other solvers, it isimportant to realize that the calling syntax is the same foreach solver in MATLAB’s suite.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    22/51

    Single First Order Differential

    Equations

    We are looking at an initial value problem of the formx’ = f (t,x), with x(t0) = x0.

    The calling syntax for using ode45 to find an approximatesolution is

    ode45(odefcn,tspan,x0),

    where odefcn calls for a functional evaluation of

      f (t,x), tspan=[t0,tfinal] is a vector containing the initial and final

    times, and x0 is the x-value of the initial condition

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    23/51

    Example 1.

    Use ode 5 to plot the

    solution of the initial value problem

    x = cos t/( 2x − 2) , x(0) = 3, (8.3)on the interval [0, 2π].

    Note that equation (8.3) is in normal form x = f (t,x), where f (t,x) = cost/(2x − 2).

    From the data we have tspan = [0,2*pi] and x0 = 3. We need to encode

    the odefcn. Open your editor and create an ODE function M-file with the contentsfunction xprime = ch8examp1(t,x)xprime = cos(t)/(2*x - 2);>> [t,x] = ode45(@ch8examp1,[0,2*pi],3);

    >> plot(t,x)>> title('The solution of x''=cos(t)/(2x - 2), with x(0) = 3.')>> xlabel('t'), ylabel('x'), grid

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    24/51

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    25/51

    Systems of First Order Equations

    Actually, systems are no harder to handle using ode45 than are singleequations.

    Consider the following system of n first order differential equations:

    x1’ = f1(t, x1, x2, . . . , xn),x2’ = f2(t, x1, x2, . . . , xn),

    ...

    xn’ = fn(t, x1, x2, . . . , xn).

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    26/51

    If we define the vector x = [x1, x2, . . . , xn]’ , system (8.6) becomes

    Finally, if we define F(t, x) = [f1(t, x), f2(t, x), . . . , fn(t, x)]T , thensystem (8.7) can be written as

    X’ = F(t, x),

    which, most importantly, has a form identical to the single first orderdifferential equation, x = f (t,x), used in Example 1. Consequently, if

    function xprime=F(t,x) is the first line of a function ODE file, it isextremely important that you understand that x is a vector with entriesx(1), x(2),..., x(n).

    Confused? Perhaps a few examples will clear the waters.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    27/51

    Example 3.

    Use ode 5 to solve the

    initial value problem

    Equation (8.9)

    on the interval [0, 10], with initial conditions x1(0) = 0 and x2(0) = 1. We can write system (8.9) as the vector equation

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    28/51

    Open your editor and create the following ODE file6.function xprime = F(t,x)

    xprime = zeros(2,1); %The output must be column vector

    xprime(1) = x(2) - x(1)^2;xprime(2) = -x(1) - 2*x(1)*x(2);

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    29/51

    Before we call ode45, we must establish the initial condition.Recall that the initial conditions for system (8.9) were given asx1(0) = 0 and x2(0) = 1. Consequently, our initial condition vector willbe

    >> [t,x] = ode45(@F,[0,10],[0;1]);

    >> plot(t,x)

    >> title('x_1'' = x_2 - x_1^2 and x_2'' = -x_1 - 2x_1x_2')

    >> xlabel('t'), ylabel('x_1 and x_2')

    >> legend('x_1','x_2'), grid

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    30/51

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    31/51

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    32/51

    Solving systems with eul rk2 and rk4.

    These solvers, introduced in Chapter 5, can also beused to solve systems. The syntax for doing so is not toodifferent from that used with ode45. For example, to solvethe system in (8.9) with eul, we use the command

    >> [t,x] = eul(@F,[0,10],[0;1],h);

    where h is the chosen step size. To use a different solver it isonly necessary to replace eul with the rk2 or rk4. Thus, theonly difference between using one of these solvers and ode45is that it is necessary to add the step size as an additionalparameter.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    33/51

    Second Order Differential Equations

    To solve a single second order differential equation it isnecessary to replace it with the equivalent first order system.For the equation

     y’’ = f (t,y,y’), (8.11)

    we set x1 = y, and x2 = y’. Then x = [x1, x2]’ is a solution tothe first order system

    x1’ = x2,

    x2’ = f (t,x1, x2).

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    34/51

    Example 4

    Plot the solution of the initial value problemY’’ + yy’ + y = 0, y(0) = 0, y’(0) = 1, on the interval [0, 10].

    First, solve the equation in (8.13) for y’’.

    Y’’ = − yy −’y ( 8.14)

    Introduce new variables for y’ and y.x1 = y and x2 = y’

    Then we have

    X1’ = y’ = x2, and x2’ = y’’ = − yy’ − y = −x1x2 − x1,

    or, more simply,X1’= x2,

    X2’ = −x1x2 − x1.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    35/51

    function xprime = dfile(t,x)xprime = zeros(2,1);

    xprime(1) = x(2);

    xprime(2) = -x(1)*x(2) - x(1);function ch8examp4

    [t,x] = ode45(@dfile,[0,10],[0;1]);

    plot(t,x(:,1))

    title('y'''' + yy'' + y = 0, y(0) = 0, y''(0) = 1')

    xlabel('t'), ylabel('y'), grid

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    36/51

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    37/51

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    38/51

    Starting odesolve

    The interface of odesolve is very similar to those found indfield and pplane. To begin, execute

    >> odesolve

    at the MATLAB prompt. This opens the ODESOLVE Setupwindow. An example can be seen in

    One of the most important is the edit box for the number ofequations.

    Change this number to 20 and depress the Tab or Enter key.The setup window expands to allow the entry of 20equations and the corresponding initial conditions.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    39/51

    Example 1. Consider the two massesm1 andm2 connected by springsand driven by an external force, as

    illustrated in Figure 9.1. In the absence of the force, each of the masses has anequilibrium position.

    Let x and y denote the displacements of the masses from their equilibrium positions, asshown in Figure 9.1.

    Plot the displacements for a variety of values of the parameters and external forces

    Analysis of the forces and Newton’s second law lead us to the system ofequationsm1*x ‘’= k2(y − x) − k1x,

    m2*y ‘’= −k2(y − x) + f (t),

    (9.1)

    where k1 and k2 are the spring constants, and f (t) is the external force.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    40/51

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    41/51

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    42/51

    Solving Ordinary Differential Equations

    Using Symbolic ToolBox

    The routine dsolve is probably the most useful differentialequations tool in the Symbolic Toolbox.

    To get a quick description of this routine, enter help dsolve.

    The best way to learn the syntax of dsolve is to look at anexample.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    43/51

    Example 3. Find the general solution of the first orderdifferential equation

    The Symbolic Toolbox easily finds the general solution of thedifferential equation in (10.3) with the command

    >> dsolve('Dy + y = t*exp(t)')

    ans =

    1/2*t*exp(t)-1/4*exp(t)+exp(-t)*C1

    Notice that dsolve requires that the differential equation beentered as a string, delimited with single quotes.

    The notation Dy is used for y’, D2y for y’’, etc.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    44/51

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    45/51

    >> y = dsolve('Dy + y = t*exp(t)','t')y =

    1/2*t*exp(t)-1/4*exp(t)+exp(-t)*C1 The command>> pretty(y)

    1/2 t exp(t) - 1/4 exp(t) + exp(-t) C1 gives us a nicer display of the output.

    Substituting values and plotting.

    Let’s substitute a number for the constant C1 and obtain a plot ofthe result on the time interval [−1, 3]. The commands

    >> syms C1;

    >> y = subs(y,C1,2)

    y =

    1/2*t*exp(t)-1/4*exp(t)+2*exp(-t)

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    46/51

    replace the variable C1 in the symbolic expression y with the value of C1 inMATLAB’s workspace. MATLAB’s ezplot command has been overloaded forsymbolic objects, and the command

    >> ezplot(y,[-1,3]) will produce an image similar to that in Figure 10.1. Execute help sym/ezplot to

    learn about the many options available in ezplot.

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    47/51

    Solving Systems of Ordinary Differential

    Equations

    The routine dsolve solves systems of equations almost as easily asit does single equations, as long

    as there actually is an analytical solution.

    Example 5. Find the solution of the initial value problem

    x ‘= −2x − 3y,

     y ‘= 3x − 2y,

    (10.5), with x(0) = 1 and y(0) = −1.

    We can call dsolve in the usual manner. Readers will note that theinput to dsolve in this example parallels that in Examples 3 and 4.The difference lies in the output variable(s).

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    48/51

    If a single variable is used to gather the output, then the Symbolic Toolbox returns a MATLAB structure5.

    A structure is an object which has user defined fields, each of which is a MATLAB object. In this case the fields are symbolic objectscontaining the components of the solution6 of system (10.5). Thus the command

    >> S = dsolve('Dx = -2*x - 3*y,Dy = 3*x-2*y', 'x(0) = 1,y(0) = -1','t')

    S =

    x: [1x1 sym]

    y: [1x1 sym]

    produces the structure S with fields

    >> S.xans =

    exp(-2*t)*(cos(3*t)+sin(3*t))

    >> S.y

    ans =

    exp(-2*t)*(sin(3*t)-cos(3*t))

    It is also possible to output the components of the solution directly with the command

    >> [x,y] = dsolve('Dx = -2*x-3*y,Dy = 3*x-2*y','x(0) = 1, y(0) = -1','t')

    x =

    exp(-2*t)*(cos(3*t)+sin(3*t))

    y =

    exp(-2*t)*(sin(3*t)-cos(3*t))

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    49/51

    Each component of the solution can be plotted versus t with the following sequence of commands.

    >> ezplot(x,[0,2*pi])

    >> hold on

    >> ezplot(y,[0,2*pi])

    >> legend('x','y')

    >> hold off 

    Adjust the view with the axis command, and add a title and axis labels.>> axis([0,2*pi,-1.2,1.2])

    >> title('Solutions of x'' = -2x-3y, y'' = 3x-2y, x(0) = 1, y(0) = -1.')

    >> xlabel('Time t')

    >> ylabel('x and y')

    This should produce an image similar to that in Figure 10.3. We used the Property Editor to makeone of the curves dashed.

    It is also possible to produce a phase-plane plot of the solution. With the structure output the basiccommand is simply ezplot(S.x,S.y). After some editing we get Figure 10.4

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    50/51

    [email protected]

  • 8/16/2019 Ordinary Differential Equations (Ode) Solving Using Matlab

    51/51