Lecture#1 Numerical UIU

Embed Size (px)

Citation preview

  • 7/24/2019 Lecture#1 Numerical UIU

    1/22

    United International University

    EEE 315: Numerical Analysis

    What is Numerical Methods?

    Numerical methods are techniques by which mathematicalproblems are formulated so that they can be solved witharithmetic and logical operations.

  • 7/24/2019 Lecture#1 Numerical UIU

    2/22

    Why should we study NumericalMethods?

    The major advantage of numerical methods is that anumerical value can be obtained even when the problemhas no analytical solution.

    The mathematical operations required are essentiallyaddition, subtraction, multiplication, and division plusmaking comparisons.

    Analytical methods, usually give a result in terms ofmathematical functions that can then be evaluated forspecific instances.

    Numerical methods always produce numerical results.

    Scope of Numerical Analysis

    Finding roots of equations

    Solving systems of linear algebric equations

    Interpolation and regression analysis

    Numerical differentiation

    Numerical Integration

    Solution of ordinary differential equations

    Boundary value problems

  • 7/24/2019 Lecture#1 Numerical UIU

    3/22

    Bungee Jump

    Modeling a bungee-jumping

    The following mathematical equations can be used tomodel the rate of change of velocity of a bungee-jumper

    where,v = downward vertical velocity (m/s),t = time (s),g = the acceleration due to gravity (=9.81m/s2),cd = drag coefficient (kg/m), andm = the jumpers mass (kg).

    2

    2

    vm

    cg

    dt

    dv

    vcF

    mgF

    FFF

    d

    dD

    m

    Dm

    =

    =

    =

    +=Force balance,

    Force of mass,

    Drag force,

    Resultantacceleration,

  • 7/24/2019 Lecture#1 Numerical UIU

    4/22

    Analytical Solution

    If the jumper is initially at rest (v=0 at t =0),calculus can be used to solve the equation of themodel

    where tanh is the hyperbolic tangent that can beeither computed directly or via the more elementaryexponential function,

    = t

    m

    gc

    c

    gmtv d

    d

    tanh)(

    xx

    xx

    ee

    eex

    +

    =)tanh(

    Numerical Solution

    ii

    ii

    tt

    tvtv

    t

    v

    dt

    dv

    =

    +

    +

    1

    1 )()(

    ( )iiid

    ii tttvm

    cgtvtv

    +=

    ++ 1

    2

    1 )()()(

    The rate change of velocity can be approximated by,

    The above equation can be rearranged as,

  • 7/24/2019 Lecture#1 Numerical UIU

    5/22

    Exact and Approximate Solution

    t, sec v(t), exact v(t), approximate

    0 0 0

    2 18.7292 19.6200

    4 33.1118 36.4137

    6 42.0762 46.2983

    8 46.9575 50.1802

    10 49.4212 51.312312 50.6175 51.6008

    Considering, m = 68.1, g = 9.81, cd = 0.25, step size = 2 sec

    Analytical Versus Numerical Solution

  • 7/24/2019 Lecture#1 Numerical UIU

    6/22

    Matlab Environment

    Matlab uses three windows: Command window Graphics window Edit window

    Command window After starting Matlab it will open command window with a prompt>> If you type>> 55-16 Matlab will display

    ans =39

    ans is an automatically generated variable>> ans + 34

    ans=73

    Assignment: scalar

    >> a = 4

    >> A = 6;

    >> a = 4, A = 6; x = 1;

    >> x = 2 + i*4

    >> x = 2+j*4

    >> pi

    >> format long [16 decimal place]>> format short [4 decimal place]

  • 7/24/2019 Lecture#1 Numerical UIU

    7/22

  • 7/24/2019 Lecture#1 Numerical UIU

    8/22

  • 7/24/2019 Lecture#1 Numerical UIU

    9/22

    logspace function

    The logspace function generates a row vector that islogarithmically equally spaced

    It has the form

    logspace(x1, x2, n)

    which generates n logarithmically equally spaced pointsbetween decades 10 x1 and 10 x2

    For example,

    >> logspace(-1,2,4)ans =

    0.1000 1.0000 10.0000 100.0000

    If n is omitted, it automatically generates 50 points.

    Character string

    Aside from numbers, alphanumeric information or character stringscan be represented by enclosing the strings within single quotationmarks. For example,

    >> f = Ehsanul';>> s = Kabir';>> x = [f s]

    x =Ehsanul Kabir

    Line continuation:>> a = [1 2 3 4 5 ...

    6 7 8]a = 1 2 3 4 5 6 7 8

    >> quote = ['Any fool can make a rule,' ...' and any fool will mind it']quote =

    Any fool can make a rule, and any fool will mind it

  • 7/24/2019 Lecture#1 Numerical UIU

    10/22

  • 7/24/2019 Lecture#1 Numerical UIU

    11/22

    Element by element multiplication

    >> A^2

    ans =

    30 36 42

    66 81 96

    102 126 150

    results in matrix multiplication of A with itself.

    What if you want to square each element of A? That can be done with

    >> A.^2ans =

    1 4 9

    16 25 36

    49 64 81

    The . preceding the operator signifies that the operation is to becarried out element by element.

    Built-in functions

    To learn about the log function, type in>> help log

    LOG Natural logarithm.LOG(X) is the natural logarithm of the elements of X.Complex results are produced if X is not positive.See also LOG2, LOG10, EXP, LOGM.

    For a list of all the elementary functions, type>> help elfun>> log(A)ans =

    0 0.6931 1.09861.3863 1.6094 1.79181.9459 2.0794 2.1972

    Most functions, such as sqrt, abs, sin, acos, tanh, and exp, operate inarray fashion.

  • 7/24/2019 Lecture#1 Numerical UIU

    12/22

  • 7/24/2019 Lecture#1 Numerical UIU

    13/22

    Customizing the Graph

    You can customize thegraph a bit with commandssuch as the following:

    >> title('Plot of v versus t')

    >> xlabel('Values of t')

    >> ylabel('Values of v')

    >> grid

    Subplot

    Subplot allows you to split the graph window into sub windows orpanes. It has the syntax

    subplot(m, n, p)

    This command breaks the graph window into an m-by-n matrix of smallaxes, and selects the pth axes for the current plot.

    First, letus graph a circle with the two-dimensional plot function usingthe parametric representation: x = sin(t) and y = cos(t). We employ thesubplot command so we can subsequently add the three-dimensionalplot.

    >> t = 0:pi/50:10*pi;

    >> subplot(1,2,1); plot(sin(t), cos(t))>> axis square

    >> title('(a)')

    The result is a circle. Note that the circle would have been distorted if wehad not used the axis square command.

  • 7/24/2019 Lecture#1 Numerical UIU

    14/22

    Subplot (continued)

    We can demonstrate subplot by examining MATLABs capability togenerate three-dimensional plots. The simplest manifestation of thiscapability is the plot3 command which has the syntax

    plot3(x, y, z)

    where x, y, and z are three vectors of the same length. The result is aline in three-dimensional space through the points whose coordinatesare the elements of x, y, and z.

    Now, let us add the helix to the graphs right pane.

    To do this, we again employ a parametric representation: x = sin(t), y =cos(t), and z=t

    >> subplot(1,2,2);plot3(sin(t),cos(t),t);>> title('(b)')

    The result is shown in next slide.

    Subplot outputs

  • 7/24/2019 Lecture#1 Numerical UIU

    15/22

    M-files

    The most common way to operate MATLAB is by enteringcommands one at a time in the command window.

    M-files provide an alternative way of performing operationsthat greatly expand MATLABs problem-solvingcapabilities.

    An M-file consists of a series of statements that can be runall at once.

    The nomenclature M-filecomes from the fact that such filesare stored with a .m extension.

    M-files come in two flavors: script files and

    function files

    Script file

    A script file is merely a series of MATLAB commandsthat are saved on a file.

    They are useful for retaining a series of commandsthat you want to execute on more than one occasion.

    The script can be executed by typing the file name inthe command window or by invoking the menuselections in the edit window: Debug, Run.

  • 7/24/2019 Lecture#1 Numerical UIU

    16/22

    Script file

    Open the editor with the menu selection:

    File, New, M-file.

    Type in the following statements

    g = 9.81; m = 68.1; t = 12; cd = 0.25;

    v = sqrt(g * m / cd) * tanh(sqrt(g * cd / m) * t)

    Save the file as scriptdemo.m.

    Return to the command window and type

    >> scriptdemo

    The result will be displayed as

    v =

    50.6175

    You can find the values of a variable used in the file, e.g., to find the value of g>> g

    g =

    9.8100

    This is an important distinction between scripts and functions

    Function Files

    function outvar= funcname(arglist)% helpcommentsstatementsoutvar= value;

    Where,outvar =the name of the output variable,Funcname =the functions name,arglist =the functions argument list (i.e., comma-delimited values

    that are passed intothe function),

    helpcomments =text that provides the user with information regarding thefunction (these can be invoked by typing help funcnameinthe command window), and

    Statements =MATLAB statements that compute the value that isassigned to outvar.

    The M-file should be saved as funcname.m.

  • 7/24/2019 Lecture#1 Numerical UIU

    17/22

    An example of function file

    function v = freefall(t, m, cd)% freefall: bungee velocity with second-order drag% v=freefall(t,m,cd) computes the free-fall velocity% of an object with second-order drag% input:% t = time (s)% m = mass (kg)% cd = second-order drag coefficient (kg/m)% output:% v = downward velocity (m/s)

    g = 9.81; % acceleration of gravityv = sqrt(g * m / cd)*tanh(sqrt(g * cd / m) * t);

    Save the file as freefall.m.

    Running a function file

    To invoke the function, return to the command window and type in

    >> freefall(12,68.1,0.25)

    The result will be displayed as

    ans =

    50.6175

    A function M-file is that it can be invoked repeatedly for different argument values.Suppose that you wanted to compute the velocity of a 100-kg jumper, after 8 s:

    >> freefall(8,100,0.25)

    ans =

    53.1878

    See what happens by issuing the folllowing two commands>> help freefall >> lookfor bungee

    Note that, at the end of the previous example, if we had typed

    >> g, the following message would have been displayed

    ??? Undefined function or variable 'g'.

  • 7/24/2019 Lecture#1 Numerical UIU

    18/22

    Function M-files returning morethan one result

    In such cases, the variables containing the results are comma-delimitedand enclosed in brackets. For example, the following function, stats.m,computes the mean and the standard deviation of a vector:

    function [mean, stdev] = stats(x)

    n = length(x);

    mean = sum(x)/n;

    stdev = sqrt(sum((x-mean).^2/(n-1)));

    Here is an example of how it can be applied:

    >> y = [8 5 10 12 6 7.5 4];

    >> [m,s] = stats(y)

    m =7.5000

    s =

    2.8137

    Sub function

    Functions can call other functions. Although such functions can exist asseparate M-files, they may also be contained in a single M-file. Forexample, :

    function v = freefallsubfunc(t, m, cd)v = vel(t, m, cd);

    end

    function v = vel(t, m, cd)g = 9.81;v = sqrt(g * m / cd)*tanh(sqrt(g * cd / m) * t);

    end This M-file would be saved as freefallsubfunc.m. In such cases, the first function is called the main or primary function. It is the only function that is accessible to the command window and

    other functions and scripts. All the other functions (in this case, vel) are referred to as subfunctions.

  • 7/24/2019 Lecture#1 Numerical UIU

    19/22

    Running a subfunction

    A subfunction is only accessible to the main function andother subfunctions within the M-file in which it resides.If we run freefallsubfunc from the command window,

    >> freefallsubfunc(12,68.1,0.25)ans =

    50.6175 However, if we attempt to run the subfunction vel, an

    error message occurs:>> vel(12,68.1,.25)

    ??? Undefined function or method 'vel' for input argumentsof type 'double'.

    TheInputfunction

    This function allows you to prompt the user for values directly fromthe command window. Its syntax is

    n = input('promptstring') The function displays the prompt string, waits for keyboard input, and

    then returns the value from the keyboard. For example,>> m = input('Mass (kg): ') When this line is executed, the user is prompted with the message

    Mass (kg):

    If the user enters a value, it would then be assigned to the variable m.

    The input function can also return user input as a string. To do this, an's is appended to the function

    s argument list. For example,>> name = input('Enter your name: ','s')

  • 7/24/2019 Lecture#1 Numerical UIU

    20/22

    The disp function

    This function provides a handy way to display a value. Its syntax isdisp(value)

    function freefallig = 9.81; % acceleration of gravitym = input('Mass (kg): ');cd = input('Drag coefficient (kg/m): ');t = input('Time (s): ');disp( ')disp('Velocity (m/s):')disp(sqrt(g * m / cd)*tanh(sqrt(g * cd / m) * t))

    Save the file as freefalli.m. To invoke the function, return to the command window and type

    >> freefalli

    Thefprintfunction

    This function provides additional control over the display of information.

    A simple representation of its syntax is

    fprintf('format', x, ...)

    A simple example would be to display a value along with a message.

    For instance, suppose that the variable velocity has a value of 50.6175. Todisplay the value using eight digits with four digits to the right of thedecimal point along with a message, the statement along with the resulting

    output would be>> fprintf('The velocity is %8.4f m/s\n', velocity)

    It will generate the output as:

    The velocity is 50.6175 m/s

  • 7/24/2019 Lecture#1 Numerical UIU

    21/22

    Commonly used format with fprintf

    Format Code Description

    %d Integer format

    %e Scientific format with lower case e

    %E Scientific format with upper case E

    %f Decimal format

    %g The more compact of %e or %E

    Control Code Description

    \n Start New line

    \t Tab

    More on fprintf

    The fprintffunction can also be used to display several values perline with different formats. For example,>> fprintf('%5d %10.3f %8.5e\n',100,2*pi,pi);

    100 6.283 3.14159e+000

    It can also be used to display vectors and matrices. Here is an M-filethat enters two sets of values as vectors. These vectors are thencombined into a matrix, which is then dis-played as a table withheadings:

    function fprintfdemo

    x = [1 2 3 4 5];y = [20.4 12.6 17.8 88.7 120.4];

    z = [x;y];fprintf(' x y \n');fprintf('%5d %10.3f \n',z);

  • 7/24/2019 Lecture#1 Numerical UIU

    22/22

    who and whos command

    At any point in a session, a list of all current variables can beobtained by entering the who command:

    >> whoYour variables are:

    A a ans b x

    or, with more detail, enter the whos command:>> whosName Size Bytes Class

    A 3x3 72 double arraya 1x5 40 double arrayans 1x1 8 double array

    b 5x1 40 double arrayx 1x1 16 double array (complex)

    Grand total is 21 elements using 176 bytes

    Thanks