lecture 20 rev 1(1)

Upload: sushant-mishra

Post on 03-Jun-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 Lecture 20 Rev 1(1)

    1/27

    ADACM Lecture #2

    1

    IntroductionIn this lecture we shall continue to use MATLAB programming to solve some applied

    dynamics problems. A summary of some fundamental MATLAB features follow next.

    An introduction to Matlab may be found at

    https://sites.google.com/a/nd.edu/jay-brockman/multimedia-2#TOC-MATLAB-Basics-

    Tutorials

    Take a look at these flash videos in your own time.

    MATLAB ProgrammingThis section describes some of the basic features of MATLAB programming. For a more

    detailed study of MATLAB, the reader is referred to the MATLAB help files (invoked by

    pressing the F1 key or typing help at the MATLAB command) or any introductory book on

    MATLAB programming for engineers and scientists.

    MATLAB is a high-level language for technical computing. It integrates computation,

    visualization, and programming in an environment where problems and solutions are

    expressed in mathematical notation. Typical application areas include:

    Mathematical and computational algorithm development Numerical modelling and simulation Data analysis and visualisation Scientific and engineering graphics Application development, including graphical user interface building Data acquisition and control in real time

    MATLAB stands for Matrix Laboratory; hence, the basic storage unit for any MATLAB

    variable is the matrix also known as an array.

    Command LineMATLAB (like the old DOS or UNIX terminal) is a command-line system. When you open

    MATLAB for the first time, you see the Command Window with the command line prompt

    >> and flashing cursor position. Individual MATLAB commands may be typed at the

    command line prompt. Or multiple commands may be written if they are separated by

    commas or semi-colons.

    WorkspaceThe Workspace window should be visible in the MATLAB window (if not, go to

    Desktop/workspace in the command list at the top).

    The workspace is the repository for any MATLAB constants or named variables that the user

    creates during the course of a MATLAB session. For example, to create a variable, letscall

    itx, and give it a value of 5 type:

    x=5

    https://sites.google.com/a/nd.edu/jay-brockman/multimedia-2#TOC-MATLAB-Basics-Tutorialshttps://sites.google.com/a/nd.edu/jay-brockman/multimedia-2#TOC-MATLAB-Basics-Tutorialshttps://sites.google.com/a/nd.edu/jay-brockman/multimedia-2#TOC-MATLAB-Basics-Tutorialshttps://sites.google.com/a/nd.edu/jay-brockman/multimedia-2#TOC-MATLAB-Basics-Tutorialshttps://sites.google.com/a/nd.edu/jay-brockman/multimedia-2#TOC-MATLAB-Basics-Tutorials
  • 8/13/2019 Lecture 20 Rev 1(1)

    2/27

    ADACM Lecture #2

    2

    at the command line. MATLAB echoes the details of the variable just created. Take a look in

    the workspace window and you will see a new variable with the name x and a value of 5.

    Because we are working in the Matrix Laboratory, x is a 1x1 dimensions array.

    To stop the automatic echo, use a semi-colon. Type

    y=9;

    and see what happens.

    To create larger arrays or matrices we use square brackets, commas (or spaces will do) and

    semi-colons. The square brackets indicate that the values are to be stored in an array.

    Commas or spaces are used to distinguish individual entries along the rows. Semi-colons are

    used to distinguish a new row. Typing

    A = [1 2 ; 3 4];

    at the command line will create a 2x2 array in the workspace.

    We can transpose a matrix (flip it about its diagonal) by using the apostrophe. Create a new

    array B which is the transpose of A by typing.

    B=A'

    The transpose function is useful for turning a row array into a column array and vice versa.

    Try

    C = [1 2 3 4 5 6]

  • 8/13/2019 Lecture 20 Rev 1(1)

    3/27

    ADACM Lecture #2

    3

    D = [1 2 3 4 5 6]

    E = [1;2;3]

    F = [1;2;3]

    Note that we can use the = command to relate variable; hence, D=C and F=E would haveworked too.

    Note that the command = is used to assign a value to a parameter. It does not mean equal

    to more later.

    To find out what variables are in the workspace at any time type the command who at the

    command prompt. The workspace can be saved and retrieved for later use. The command

    clear is useful for removing all variables from the workspace.

    MATLAB Path

    When you open MATLAB you see a window called current directory. This currentdirectory has a location on the hard drive as C:\MATLAB7\work (depending on the version

    of MATLAB installed). The current directory is always \work by default. You can

    change the working directory at any other location. MATLAB files in the current directory

    are always visible to MATLAB. If MATLAB files are stored outside of the current directory

    then they must be in file locations that are designated on the MATLAB path. Otherwise,

    MATLAB will not be able to run these files. To see the path type path at the command

    prompt or go to file\set path on the command list at the top. By taking the latter approach,

    one can add or remove file locations to the MATLAB path.

    Command History

    The other window usually visible on the MATLAB window is called Command History. Thiswindow stores the list of previous MATLAB commands from the current session and

    previous sessions. The up and down arrow keys ( and ) may be used at the command

    prompt to toggle through previous commands.

    MATLAB FilesFiles that contain code in the MATLAB language are called M-files. You create M-files

    using a text editor, then use them as you would any other MATLAB function or command.

    There are two kinds of M-files:

    1. Scripts, which do not accept input arguments or return output arguments. Theyoperate on data in the workspace.

    2. Functions, which can accept input arguments and return output arguments. Internalvariables are local to the function.

    If you're a new MATLAB program, just create the M-files that you want to try out in the

    current directory. As you develop more of your own M-files, you will want to organize them

    into other directories and personal toolboxes that you can add to your MATLAB path. If you

    duplicate function or script file names, MATLAB executes the one that occurs first in the

    search path.

  • 8/13/2019 Lecture 20 Rev 1(1)

    4/27

    ADACM Lecture #2

    4

    MATLAB script filesScripts files (or batch files) are lists of commands that are operated in a sequence. The

    sequence or flow is controlled by the code, but the default sequence is to complete each

    command one at a time... more on this topic later.

    Last week we wrote a few of our own script files to solve for axle loads. An important pointabout file name, they should be a single string of characters (no spaces allowed) followed by

    the extension .m. To run the script file you can use the MATLAB editor/debug commands

    or type the file name without the .m extension at the MATLAB command line prompt.

    You may call a script file command from within another script file.

    MATLAB Function filesFunctions are M-files that can accept input arguments and return output arguments. The

    names of the M-file and of the function should be the same. Functions operate on variables

    within their own workspace, separate from the workspace you access at the MATLAB

    command prompt. A good example is provided by the command rank. The M-file rank.m isavailable in the directory toolbox/matlab/matfun

    You can see a file with the command type followed by the filename.

    In our case insert typerank

    Here is the file as written in MATLAB.

    function r = rank(A,tol)

    % RANK Matrix rank.

    % RANK(A) provides an estimate of the number of linearly

    % independent rows or columns of a matrix A.

    % RANK(A,tol) is the number of singular values of A

    % that are larger than tol.

    % RANK(A) uses the default tol = max(size(A)) * norm(A) * eps.

    s = svd(A);

    if nargin==1

    tol = max(size(A)') * max(s) * eps;

    end

    r = sum(s > tol);

    The first line of a function M-file starts with the keyword function. It gives the function name

    and order of arguments. In this case, there are up to two input arguments and one output

  • 8/13/2019 Lecture 20 Rev 1(1)

    5/27

    ADACM Lecture #2

    5

    argument. The next several lines, up to the first blank or executable line, are comment lines

    that provide the help text. These lines are printed when you type help rank

    The rest of the file is the executable MATLAB code defining the function. The variable s

    introduced in the body of the function, as well as the variables on the first line, r, A and tol,

    are all local to the function; they are separate from any variables in the MATLAB workspace.

    This example illustrates one aspect of MATLAB functions that is not ordinarily found in

    other programming languages -- a variable number of arguments. The rank function can be

    used in several different ways. rank(A)

    r = rank(A)

    r = rank(A,1.e-6)

    Many M-files work this way. If no output argument is supplied, the result is stored in the

    default variable ans. If the second input argument is not supplied, the function computes a

    default value.

    Flow ControlUsing programming statements we can control the flow or sequence of commands in

    MATLAB.

    The most widely used conditional flow statement is the ifstructure.

    The first of these to look at is the if-endstructure

    It can be written in code seen in figure 1 below. The figure shows how the commands are

    types into the program, and the flowchart symbolically shows the flow. Or the sequence, in

    which the commands are executed. As the program executes, it reached the if statement.

    If the conditional expression is true (1), the program continues to execute the commands that

    follow the if statement all the way down to the end statement.

    If the conditional expression is false (0), the program skips the commands that follow the if

    statement all the way down to the end statement, and continues with the commands that

    follow the end.

    So, if we had the following problem of calculating a workers pay. Lets say that a worker is

    paid according to his hourly wage up to 40 hours, and 50% more for over time above the 40

    hours. Write a program in a script file that calculates the pay to a worker. The program has to

    ask the user to enter the number of hours and the hourly wage. The program is then to display

    the pay.

  • 8/13/2019 Lecture 20 Rev 1(1)

    6/27

    ADACM Lecture #2

    6

    If

    Statement

    Commands

    True

    False

    Flowchart

    End

    ..

    .. MATLAB program

    .

    if conditional expression

    ..

    ..

    ..

    end

    ..

    .. MATLAB program

    .

    Figure 1: the structure of the if-else conditional statement

    %Script file: pay.m%%Purpose

    % This program calculates the pay of a worker for a given number of% hours. If the number of hours is over 40 hours, then a weighting of% 50% extra is given on base salary for the extra hours%%Record of revisions:% Date Programmer Description of Change% ==== ========== =====================% 25/12/20212 Gerard Nagle Original code%%Define Variables:% t -Number of hours Worked% h -Hourly wage% Pay -Calculated Pay

    t=input('Please enter the number of hours worked ');h=input('please enter the hourly wage in ');Pay=t*h;ift>40

    Pay=Pay+(t-40)*0.5*h;endfprintf('The workers pay is $%5.2f', Pay)

  • 8/13/2019 Lecture 20 Rev 1(1)

    7/27

    ADACM Lecture #2

    7

    Note onfprintf

    The fprintf can be used to display output (text and data) on to the MATLAB command

    window or save it to a file. This command allows the output to be formatted. Also text and

    data can be intermixed and displayed on the same line.

    fprintf(text as string %-5.2f additional text, variable name)

    The % sign marks the

    spot where the number

    is inserted within the text

    Formatting elements.

    (These define the format

    of the number)

    The name of the

    variable whose value is

    displayed

    And the formatting elements are;

    -5.2f

    Flag

    (optional)

    Field width and precision

    (optional)

    Conversion character

    (required!)

    Where the flag is;

    - (minus sign) Left justify within the field+ (plus sign) Prints a character (+ or -) in front of the number)

    0 (zero) adds zeros if the number is shorter than the field.

    Conversion character

    E or e is exponential using upper or lower case

    f is fixed point notation

    i is integer

  • 8/13/2019 Lecture 20 Rev 1(1)

    8/27

    ADACM Lecture #2

    8

    if-else-endThe ifstatement evaluates a logical expression and executes a group of statements when the

    expression is true. The first line if an if statement with a conditional expression. If the

    conditional expression is true (1), the program

    If

    Statement

    Commands

    Group 1

    True

    False

    Flowchart

    End

    ..

    .. MATLAB program

    .

    if conditional expression

    ..

    ..

    ..

    else

    ..

    ..

    ..

    end

    ..

    ..MATLAB program

    Commands

    Group 2Group 2 of

    MATLAB commands

    Group 1 of

    MATLAB commands

    A water tank has the geometer as shown in the figure below. The lower part is a cylinder, and

    the upper part is an inverted frustum cone. There is a float in the tank that indicates the level

    of the water. We have to write a function that determines the volume of the water in the tank

    from the height of the water in the tank.

    Diameter 25 m

    19 m

    14m

    Diameter 46 m

    rh

    h

  • 8/13/2019 Lecture 20 Rev 1(1)

    9/27

    ADACM Lecture #2

    9

    %Function file: watervol.m%%Purpose% This programme calculates the volume of water in a water tower.% The dimensions of the tower are as in that attached diagram.%%%Record of revisions:% Date Programmer Description of Change% ==== ========== =====================% 25/12/2012 Gerard Nagle Original code%%Define Variables:% h -Height of Water in tower% rh -radius of upper inverted frustum cone

    functionv = watervol(h)ifh

  • 8/13/2019 Lecture 20 Rev 1(1)

    10/27

    ADACM Lecture #2

    10

    If

    Statement

    Commands

    Group 1

    True

    False

    Flowchart

    End

    Commands

    Group 2

    Commands

    Group 3

    elseif

    Statement

    True

    False

    ..

    .. MATLAB program

    .

    if conditional expression

    ..

    ..

    ..

    elseif

    ..

    ..

    ..

    else

    ..

    ..

    ..

    end

    ..

    ..MATLAB program

    Group 2 of

    MATLAB commands

    Group 1 of

    MATLAB commands

    Group 3 of

    MATLAB commands

    %Script file: calc_roots.m

    %Script file: calc_roots.m%%Purpose% This program solves for the roots of a quadratic equation of the form% a*x**2 + b*x + c = 0. It calculates the answers regardless if the type% of roots that the equation possesses% %%%Record of revisions:% Date Programmer Description of Change% ==== ========== =====================% 25/12/20212 Gerard Nagle Original code%%Define Variables:% a -Coefficient of the x^2 term% b -Coefficient of the x term% c -Constant term of the equation% discriminant -Discriminant of the equation% imag_part -Imag part of the equation (for complex roots)% real_part -Real part of the equation (for complex roots)% x1 -First Solution of equation (for real roots)

  • 8/13/2019 Lecture 20 Rev 1(1)

    11/27

    ADACM Lecture #2

    11

    % x2 -Second Solution of equation (for real roots)

    %prompt the user for the coefficients of the equationdisp ('This program solves for the roots of a quadratic ');disp ('equation of the form A*X^2 + B*X + C = 0.');a=input('Enter the coefficient A: ');b=input('Enter the coefficient B: ');c=input('Enter the coefficient C: ');

    % Calculate the discriminantdiscriminant = b^2 -4 * a * c;

    %solve for the roots, depending on the values of the discriminantifdiscriminant > 0 % there are two real roots, so we have

    x1 = ( -b + sqrt(discriminant))/(2 *a);x2 = ( -b - sqrt(discriminant))/(2 *a);disp ('This equation has two real roots:')fprintf ('x1 = %f\n', x1);fprintf ('x2 = %f\n', x2);

    elseifdiscriminant == 0 % there is a repeated root, so we havex1 = ( -b )/(2 *a);disp ('This equation has two identical roots:')fprintf ('x1 = x2 %f\n', x1);

    else % there is are complex roots, so we havereal_part = ( -b )/(2 *a);imag_part = sqrt ( abs ( discriminant ) ) /( 2 * a );disp ('This equation has two complex roots:')fprintf ('x1 = %f +i %f\n', real_part, imag_part );fprintf ('x2 = %f -i %f\n', real_part, imag_part );

    end

    Loop ControlsSometimes we want MATLAB to commands or complete sections of code. This can be

    achieved by using the while and for statements.

    for-endstatementThe for loop repeats a group of statements a fixed, predetermined number of times. A

    matching end delineates the statements.

    for n = 3:32

    compute these commands

    end

    The variable n starts at a value of 3 and increases automatically for each iteration by 1 until it

    reaches 33 whereupon it exits the loop without executing the commands within the loop.

    The variable n could be made to increment by a different amount.

    For n = 3:2:32

  • 8/13/2019 Lecture 20 Rev 1(1)

    12/27

    ADACM Lecture #2

    12

    Would make n increase by 2 after each iteration.

    It is a good idea to indent the loops for readability, especially when they are nested.

    for i = 1:m

    for j = 1:n

    H(i,j) = 1/(i+j);

    end

    end

    Example

    lets use afor-end loop in a script file to calculate the sum of the first n terms of the series

    1

    1

    2

    kn

    kk

    K

    . Check the script file for 4n and 20n

    for 4n , the sum is -0.125 and for 20n the sum is -0.222216

    %Script file: sum_n_terms.m%%Purpose% This program calculates the sum of the n terms of the equation given in% the text%%%%Record of revisions:% Date Programmer Description of Change% ==== ========== =====================% 25/12/20212 Gerard Nagle Original code%%Define Variables:% n -Number of terms% S -The sum output

    n = input('Enter the number of terms ');S=0;ticfork=1:n

    S=S+(-1)^k*k/(2^k);endtocfprintf('The sum of the series is: %f',S)

    %Function file: Tsin.m

  • 8/13/2019 Lecture 20 Rev 1(1)

    13/27

    ADACM Lecture #2

    13

    ..

    .. MATLAB program

    .

    for conditional expression

    ..

    ..

    ..

    end

    Group of

    MATLAB commands

    for

    conditional statement

    START

    MATLAB program

    Group of

    MATLAB

    commands

    END

    The function sin x can be written as a Taylor series by the function

    2 1

    0

    1sin

    2 1 !

    k k

    k

    xx

    k

    Write a user defined function file that calculates sin x by using the Taylors series. For the

    function name and argument, use Tsin x,ny . The input arguments are the angle x in

    degrees, and n the number of terms in the series.

    %Function file: Tsin.m%%Purpose% This program calculates the sin(x) with input arguments of x in degrees% and n, the number of terms in the Tatylor series%%%%Record of revisions:% Date Programmer Description of Change% ==== ========== =====================% 25/12/2012 Gerard Nagle Original code%%Define Variables:% x -Angle in degrees% n -Number of terms% y -The output

    functiony=Tsin(x,n)xr = x*pi/180;y = 0;fork = 0:n-1

    y = y + (-1)^k*xr^(2*k+1)/factorial(2*k+1);end

  • 8/13/2019 Lecture 20 Rev 1(1)

    14/27

    ADACM Lecture #2

    14

    While StatementThe while loop repeats a group of statements an indefinite number of times under the control

    of a logical expression. The logical expression is tested and if it is true then the loop restarts

    repeats the statements.

    while expression

    Repeat this code each time the expression is true

    end

    ..

    .. MATLAB program

    .

    while conditional expression

    ..

    ..

    ..

    end

    Group of

    MATLAB commands

    while

    conditional statement

    START

    MATLAB program

    Group of

    MATLAB

    commands

    END

    The function xf x e can be represented by the Taylor series0 !

    nx

    n

    xe

    n

    . We need to

    write a script file that calculates xe by using the Taylor series. The program calculates xe by

    adding terms of the series and stopping when the absolute value of the terms that was added

    last is smaller than 0.0001. We are required to use a while-endloop, but limit the number of

    passes to 30 (this is an arbitrary number). If in the 30th pass, the value of the term that is

    added is not smaller than 0.0001, then the program stops and displays a message that more

    than 30 terms are needed.

  • 8/13/2019 Lecture 20 Rev 1(1)

    15/27

    ADACM Lecture #2

    15

    %Script file: taylor_series_exp(x).m%%Purpose% This program solves for the exp(x) by using the Taylor series% represenation. Thr program cacluates exp(x) by adding terms of the

    % series until the absolute values of the last term added is smaller% than 0.0001%%Record of revisions:% Date Programmer Description of Change% ==== ========== =====================% 25/12/20212 Gerard Nagle Original code%%Define Variables:% x -Value of exp(x) to be calaculated% n -Value of incremenation of Taylor series% an -Value of each term in the Taylor series at each loop% S -The Sum of the Taylor series

    %prompt the user for x in the exp(x)('This program solves for exp(x) by the Taylor Series Expansion ');x = input ('Enter x ')

    %Declare the initial variablesn = 1;an = 1;S = an;

    %Start of the while loop%The conditional statement has two relational and one logical operatorwhile(abs(an) >= 0.0001) && (n = 30disp('Maore than 30 terms are needed')

    elsefprintf('exp(%f) = %f',x,S)fprintf('\nThe number of terms used is:%i',n)end

    Logical and relational expressionsThe following are the possible relational expressions used for controlling flow

    A < B (is A less than B)

    A > B (is A greater than B)

    A

  • 8/13/2019 Lecture 20 Rev 1(1)

    16/27

    ADACM Lecture #2

    16

    A >= B (is A greater than or equal to B)

    A = = B (is A equal to B)

    A ~= B (is A not equal to B)

    The logical operators are AND, OR, and NOT

    A & B (is A and B true)

    A | B (is A or B true)

    ~A (NOT A)

    The following truth table determines the responses from each logical test (1 is true and 0 is

    false)

    Flowcharts

    Flowcharts give useful graphical representations of algorithms. We can study the logic of an

    algorithm if we draw its flowchart.

    In the flowchart we use flow lines and shapes to distinguish the control of the algorithm.

    Typical symbols used in programming are given below

    Start or end of the program,

    subroutine, or function

    A process such as a computation or

    an assignment

    A decision process, where a choice is

    made

  • 8/13/2019 Lecture 20 Rev 1(1)

    17/27

    ADACM Lecture #2

    17

    Alternative to MATLAB

    GNU Octave is open-source code that is Matlab portable. It will have a different interface to

    Matlab, but should run the code with little or no changes required. For those who cannot getregular access to DIT computers, download GNU active for free.

    Exercise #5An electric motor has a power rating of 6 kW and can produce a peak torque of 27.5 Nm.

    Write a function that in Matlab that returns the maximum available torque from the motor

    (Nm) for any given speed (rad/s).

    Use this function in a Matlab script file that plots the motor torque-speed characteristic.

    A subroutine or external function that

    is documented elsewhere

    When it is inconvenient to connect

    two points use connector with a

    reference number

    A counting or iterative loop, such as

    a for loop

  • 8/13/2019 Lecture 20 Rev 1(1)

    18/27

    ADACM Lecture #2

    18

    Ordinary Differential Equations

    In mathematics, an ordinary differential equation is one which involves the derivative of a

    function, the function itself, and (sometimes) the independent variable. As an example

    consider the equation

    ( )

    Where u is the dependent variable and is a function of time, t. The equation tells us that the

    time rate of change of the function (or first derivative with respect to time) is dependent on

    the value of u at that time and on the independent time value.

    The differential equation is called ordinary because u is a function of one variable only and

    the derivatives are complete, or ordinary, differentials. The order of the differential is given

    by the order of the highest derivative in the equation; hence, for our example, the equation is

    a first-order differential equation.

    The solution of a differential equation is a function that satisfies the equation and also initial

    conditions: this is known as a starting-value problem. The requirement to know the initial

    conditions is determined by the order of the equation a first order equation requires one

    initial condition, a second order equation requires two, and so on.

    Numerical Integration Methods

    For many straight-forward ODEs we can find an analytical solution to the problem, that is,

    we can find a closed-form exact solution that satisfies the ODE and by adjusting some

    constants we can satisfy the initial conditions. For example, the following ODE and IC

    ()

    has the following analytical solution

    However, in many cases, as the ODE becomes more complicated, the analytical solution is

    unknown or too difficult to solve. In this instance a numerical solution may be your only

    choice of solution.

  • 8/13/2019 Lecture 20 Rev 1(1)

    19/27

    ADACM Lecture #2

    19

    Our procedure for solving an ODE numerically applies to first-order ODEs. If our underlying

    equation is a higher-order ODE then we substitute for derivatives with parameters until we

    get a set of first order ODEsmore on this topic later.

    Euler Integration

    Euler integration is the simplest form of integration method. It is called a single step or

    explicit method of integration, where we estimate the value of our function at the next time

    using the data at the current time step. If our first order ODE is given as

    ( ) ()

    Or ,y F x y

    Let us consider the problem of approximating a continuous function y f x on 0x

    which satisfies the differential equation

    ,y F x y

    On 0x , with the initial condition

    0y

    In which is a given constant. Taking Eulers method, we go back to the definition of a

    derivative

    0limh

    f x h f xy x

    h

    For small 0h , then we can say that a reasonable quotient approximation for y x is

    f x h f x

    y xh

    Which can be restated as

    ,f x h f x

    F x yh

  • 8/13/2019 Lecture 20 Rev 1(1)

    20/27

    ADACM Lecture #2

    20

    It can be rewritten as

    ,f x h f x hF x y

    Or equivalently as

    ,y x h y x hF x y x

    Which enables us to approximate y x h in terms of y x and ,F x y x . The equation

    above is a corner stone of Eulers method.

    Since a computer cannot calculate indefinably, we let 0x be replaced by 0 x L , in

    which L is a positive constant. The value of L is determined by the problem under

    consideration. Regardless, L is a fixed, positive constant. The interval 0 x L is divided

    into n equal parts, each a length of h , by the points , 0,1,2,...,ix ih i n . The valueL

    hn

    is called the grid size. The points ix are called grid points. Let , 0,1,2,...,i iy y x i n so

    that the initial condition (IC) implies 0y . Next, at each of the grid points

    0 1 2 1, , ,..., ,nx x x x approximate the difference equations by the notation

    1 , 0,1,2, ..., 1,i i i iy y

    F x y i nh

    Or, in explicit recursive form

    1 , 0,1,2,..., 1,i i i iy y hF x y i n

    Then, beginning with

    0y

    Set 0i and determine1

    y .

    Knowing1

    y , set 1i and determine 2y

    Knowing 2y , set 2i and determine 3y

    And so on

  • 8/13/2019 Lecture 20 Rev 1(1)

    21/27

    ADACM Lecture #2

    21

    The resulting discrete function

    0 1 2, , ,..., ny y y y

    Is called the numerical solution

    So, lets look at a problem.

    We have the initial value problem,

    y y x 0 1y

    This is a linear problem that can be solved exactly to have the solution 1 2 xY x x e

    As there is a solution to the problem, there is no need to actually solve the equation, but we

    will do so to show the technique.

    So, for Eulers method, 1L and 0.2h . Then 0 0.0,x 1 0.2,x 2 0.4,x 3 0.6,x

    4 0.8,x 5 1.0x and the difference equation is approximated by

    1 , 0,1,2,3,4,

    0.2

    i ii i

    y yy x i

    Or, if we rearrange, we get

    1 0.8 0.2 , 0,1,2,3,4,i i iy y x i

    Since 0 1y , we can calculate the equation above

    1 0 0

    2 1 1

    3 2 2

    4 3 3

    5 4 4

    0.8 0.2 0.8 1.000 0.2 0.0 0.800

    0.8 0.2 0.8 0.800 0.2 0.2 0.680

    0.8 0.2 0.8 0.680 0.2 0.4 0.624

    0.8 0.2 0.8 0.624 0.2 0.6 0.619

    0.8 0.2 0.8 0.619 0.2 0.8 0.655

    y y x

    y y x

    y y x

    y y x

    y y x

    Thus the numerical approximation with 0.2h is

  • 8/13/2019 Lecture 20 Rev 1(1)

    22/27

    ADACM Lecture #2

    22

    0.0 1.000

    0.2 0.800

    0.4 0.680

    0.6 0.6240.8 0.619

    1.0 0.655

    y

    y

    y

    yy

    y

    The exact solution is, rounded to three decimal places

    0.0 1.000

    0.2 0.837

    0.4 0.7410.6 0.698

    0.8 0.699

    1.0 0.736

    y

    y

    yy

    y

    y

    This can be seen in the plot below.

    y

    x

    nx nx h

    ny

    1ny

    True y value from

    analytical solution

    y value from

    Eulers Method

  • 8/13/2019 Lecture 20 Rev 1(1)

    23/27

    ADACM Lecture #2

    23

    With 0.1h , find the numerical solution on 0 1x by Eulers Method for

    2 42 ,y y x x 0 0y

    And compare your results to the exact solution 2y x

    With 0.1h , find the numerical solution on 0 2x by Eulers Method for

    3 38 2,y y x 0 0y

    And compare your results to the exact solution 2y x

    Modified Euler

    We can improve upon the Euler integration by getting the arithmetic average of the slope at

    the beginning and the end of the interval.

    ' '

    , 1 3

    , 12

    p n

    c n n

    y yy y h e h

    The procedure in this process is two-fold, we use the Euler method to the predict the first

    value of yp,n+1and yp,n+1. We then use the above equation to calculate the corrected value of

    yc,n+1. This method is called a predictor-corrector method and the order of the local error is

    increased to three, which means that reductions in the step will yield more accurate results

    that the basic Euler method.

    Exercise #6

    Take for example, the following ODE and IC

    dyx y

    dx , 0 1y

    Which has the following analytical solution

    2 1x

    y e x

  • 8/13/2019 Lecture 20 Rev 1(1)

    24/27

    ADACM Lecture #2

    24

    We can use the analytical solution (or exact solution) to check the accuracy of our numerical

    integration scheme. Note that an analytical solution is not always available and the only

    method is to use a numerical method.

    Let us use a table to get the answers. We shall use a integration step, h= 0.02.

    n xn yn yn hyn Exact y(x)

    1 0 1.0000 1.0000 0.0200 1.0000

    2 0.02 1.0200 1.0400 0.0208 1.020403

    3 0.04 1.041622

    4 0.06 1.063673

    Complete the table.

    Write a piece of Matlab code that completes the integration table above

    Exercise #7 Modified Euler

    The procedure in this process is two-fold, we use the Euler method to the predict the first

    value of yp,n+1and yp,n+1. We then use the above equation to calculate the corrected value of

    yc,n+1. This method is called a predictor-corrector method and the order of the local error is

    increased to three, which means that reductions in the step will yield more accurate results

    that the basic Euler method.

    We shall repeat the previous exercise using the modified Euler method.

    n xn yn yn hyn yn+1 yn+1

    ' '

    , 1

    2

    p ny yh

    1 0 1.0000 1.0000 0.0200 1.0200 1.0400 0.0204

    1.0204** 1.0404 0.0204

    2 0.02 1.0204 1.0404 0.0208 1.0412 1.0812 0.0212

    1.0416 1.0816 0.0212

    3 0.04 1.0416 1.0816 0.0216 1.0632 1.1232 0.0220

    1.0636 1.1236 0.0221

    4 0.06 1.0637 1.1237 0.02247 1.1462

  • 8/13/2019 Lecture 20 Rev 1(1)

    25/27

    ADACM Lecture #2

    25

    * The first row shows the value given by the Euler method (predicted value)

    ** The second row in shows the value calculated by the Modified Euler (corrected value)

    Complete the table and find estimated value for x = 0.08.

    Write a piece of Matlab code that completes the integration table above

    Runge-Kutta

    A further advance on the Euler method is to use the Runge-Kutta method. Here we shall

    present the fourth-order Runge-Kutta method: this one of the most widely used integration

    methods.

    1 1 2 3 41

    2 26

    n ny y k k k k

    1 ,n nk hf x y

    2 , 1

    1 1,

    2 2n n

    k hf x h y k

    3 , 2

    1 1,

    2 2n n

    k hf x h y k

    4 3,n nk hf x h y k

  • 8/13/2019 Lecture 20 Rev 1(1)

    26/27

    ADACM Lecture #2

    26

    Exercise #8

    Using Matlab solve the equation

    dyx ydx , 0 1y

    Solve for 10x , this time take 0.1h . Compare with the exact solution.

    Hint: Solution (by hand) for 0.1x (step 1)

    Calculate1

    k

    1 ,n nk hf x y

    1 0.1 0 1 0.100k

    Calculate 2k

    2 , 1

    1 1,

    2 2n n

    k hf x h y k

    21 1

    0.1 0 0.1 1 0.1 0.1 0.05 1.05 0.1102 2

    k

    Calculate 3k

    3 , 2

    1 1,

    2 2n nk hf x h y k

    31 1

    0.1 0 0.1 1 0.110 0.1 0.05 1.055 0.11052 2

    k

    Calculate 4k

    4 3,n nk hf x h y k

    4 0.1 0 0.1 1 0.1105 0.1 0.1 1.1105 0.12105k

  • 8/13/2019 Lecture 20 Rev 1(1)

    27/27

    ADACM Lecture #2

    Calculate1ny

    1 1 2 3 41

    2 26

    n ny y k k k k

    11 1

    1.0 0.1 2 0.110 2 0.1105 0.12105 1.0 0.66205 1.110346 6

    ny