You are on page 1of 22

2/18/2014

EEE 315: Numerical Analysis

United International University

What is Numerical Methods?


 Numerical methods are techniques by which mathematical

problems are formulated so that they can be solved with


arithmetic and logical operations.

2/18/2014

Why should we study Numerical


Methods?
 The major advantage of numerical methods is that a

numerical value can be obtained even when the problem


has no analytical solution.
 The mathematical operations required are essentially
addition, subtraction, multiplication, and division plus
making comparisons.
 Analytical methods, usually give a result in terms of
mathematical functions that can then be evaluated for
specific 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

2/18/2014

Bungee Jump

Modeling a bungee-jumping
 The following mathematical equations can be used to

model the rate of change of velocity of a bungee-jumper


Force balance,

F = Fm + FD

Force of mass,

Fm = mg

Drag force,

FD = c d v 2

Resultant
acceleration,

c
dv
= g d v2
dt
m

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

2/18/2014

Analytical Solution
 If the jumper is initially at rest (v=0 at t =0),

calculus can be used to solve the equation of the


model
gc d
gm
v (t ) =
tanh
t
cd
m

where tanh is the hyperbolic tangent that can be


either computed directly or via the more elementary
exponential function,

e x ex
tanh( x) = x
e + e x

Numerical Solution
The rate change of velocity can be approximated by,

dv v v(t i +1 ) v(t i )

=
dt t
t i +1 t i
The above equation can be rearranged as,
c

v(t i +1 ) = v (t i ) + g d v (t i ) 2 (t i +1 t i )
m

2/18/2014

Exact and Approximate Solution


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

v(t), exact

v(t), approximate

0
2

0
18.7292

0
19.6200

4
6

33.1118
42.0762

36.4137
46.2983

8
10
12

46.9575
49.4212
50.6175

50.1802
51.3123
51.6008

Analytical Versus Numerical Solution

2/18/2014

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]

2/18/2014

Assignment: Array, Vector


 An array is a collection of values that are represented by a

single variable name.


 One-dimensional arrays are called vectors and
 Two-dimensional arrays are called matrices.
 Row vector : >> a = [1 2 3 4 5]
 Column vector : >> b = [1; 2; 3; 4; 5]
OR >> b = [ 1
2
3
4
5]
OR >> b =[1 2 3 4 5]

Assignment: Matrices
>> A = [1 2 3; 4 5 6; 7 8 9]
OR
>> A = [ 1 2 3
456
7 8 9]
OR
>> A = [ [ 1 4 7 ]' [ 2 5 8 ]' [ 3 6 9 ]' ]
 Accessing an individual element of a vector
>> b(4)
 Accessing an individual element of a matrix
>> A(2,3)
 Built-in functions to generate vector or matrix
>> ones (2 , 3)
>> zeros (1 , 4)

2/18/2014

Assignment: Matrices (continued)


The colon operator

Colon separating two numbers generates the numbers between them with
an increment of one:
>> t = 1 : 5
t=
1 2 3 4 5
 Colons separating three numbers generate the numbers between the first
and third numbers using an increment equal to the second number:
>> t = 1 : 0.5 : 3
t=
1.0000 1.5000 2.0000 2.5000 3.0000
 Negative increments can also be used
>> t = 10 : -1 : 5
t=
10 9 8 7 6 5


linespace function
 The linspace and logspace functions provide other handy

tools to generate vectors of spaced points. The linspace


function generates a row vector of equally spaced points.
It has the form
linspace(x1, x2, n)
 which generates n points between x1 and x2. For example
>> linspace(0,1,6)
ans =
0 0.2000 0.4000 0.6000 0. 8000 1.0000
 If the n is omitted, the function automatically generates
100 points.

2/18/2014

logspace function
 The logspace function generates a row vector that is

logarithmically equally spaced


 It has the form
logspace(x1, x2, n)
which generates n logarithmically equally spaced points
between 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 strings

can be represented by enclosing the strings within single quotation


marks. For example,
>> f = Ehsanul';
>> s = Kabir';
>> x = [f s]
x=
Ehsanul Kabir
 Line continuation:
>> a = [1 2 3 4 5 ...
6 7 8]
a=12345678
>> 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

2/18/2014

Mathematical Operations
 Operations with scalar quantities are handled in a

straightforward manner, similar to other computer


languages. The common operators, in order of
priority, are
Operators

Meaning

Exponentiation

Negation

* /

Multiplication and Division

Left division

+ -

Addition and Subtraction

Inner and Outer products


 The inner product of two vectors (dot product) can be calculated

using the * operator,


>> a * b
ans=
110
 and likewise, the outer product
>> b * a
ans =
2
4
6
8
4
8
12
16
6
12
18
24
8
16
24
32
10
20
30
40

10
20
30
40
50

 Matrices cannot be multiplied if the inner dimensions are unequal.

10

2/18/2014

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.^2
ans =
1
16
49


4
25
64

9
36
81

The . preceding the ^operator signifies that the operation is to be


carried 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.0986
1.3863 1.6094 1.7918
1.9459 2.0794 2.1972
 Most functions, such as sqrt, abs, sin, acos, tanh, and exp, operate in
array fashion.

11

2/18/2014

Built-in functions (continued)


 There are several functions for rounding. For example, suppose that we enter

a vector:
>> E = [-1.6 -1.5 -1.4 1.4 1.5 1.6];
>> round(E)
ans =
-2 -2 -1 1 2 2
>> ceil(E)
ans =
-1 -1 -1 2 2 2
>> floor(E)
ans =
-2 -2 -2 1 1 1
 There are also functions that perform special actions on the elements of
matrices and arrays. For example, the sum function returns the sum of the
elements:
>> F = [3 5 4 6 1];
>> sum(F)
>> min(F), max(F), mean(F), prod(F), sort(F)

Graphics
 MATLAB allows

graphs to be created
quickly and
conveniently. For
example, to create a
 graph of the t and v
arrays from the data
above, enter
 >> plot(t, v)
 The graph appears in
the graphics window
and can be printed or
transferred via the
clip-board to other
programs

12

2/18/2014

Customizing the Graph




You can customize the


graph a bit with commands
such 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 or
panes. It has the syntax
subplot(m, n, p)
 This command breaks the graph window into an m-by-n matrix of small
axes, and selects the pth axes for the current plot.
 First, let us graph a circle with the two-dimensional plot function using
the parametric representation: x = sin(t) and y = cos(t). We employ the
subplot command so we can subsequently add the three-dimensional
plot.
>> 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 we
had not used the axis square command.


13

2/18/2014

Subplot (continued)
We can demonstrate subplot by examining MATLABs capability to
generate three-dimensional plots. The simplest manifestation of this
capability 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 a
line in three-dimensional space through the points whose coordinates
are 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

14

2/18/2014

M-files
 The most common way to operate MATLAB is by entering






commands one at a time in the command window.


M-files provide an alternative way of performing operations
that greatly expand MATLABs problem-solving
capabilities.
An M-file consists of a series of statements that can be run
all at once.
The nomenclature M-file comes from the fact that such files
are 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 commands

that are saved on a file.


 They are useful for retaining a series of commands
that you want to execute on more than one occasion.
 The script can be executed by typing the file name in
the command window or by invoking the menu
selections in the edit window: Debug, Run.

15

2/18/2014

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)
% helpcomments
statements
outvar= value;
Where,
outvar
Funcname
arglist

=the name of the output variable,


=the functions name,
=the functions argument list (i.e., comma-delimited values
that are passed into

the function),
helpcomments =text that provides the user with information regarding the
function (these can be invoked by typing help funcname in
the command window), and
Statements
=MATLAB statements that compute the value that is
assigned to outvar.
The M-file should be saved as funcname.m.

16

2/18/2014

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 gravity
v = 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'.

17

2/18/2014

Function M-files returning more


than one result
In such cases, the variables containing the results are comma-delimited
and 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 as
separate M-files, they may also be contained in a single M-file. For
example, :
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.

18

2/18/2014

Running a subfunction
 A subfunction is only accessible to the main function and

other 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 arguments
of type 'double'.

The Input function


 This function allows you to prompt the user for values directly from

the 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 functions argument list. For example,


>> name = input('Enter your name: ','s')

19

2/18/2014

The disp function


 This function provides a handy way to display a value. Its syntax is

disp(value)
function freefalli
g = 9.81; % acceleration of gravity
m = 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

The fprint function


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. To
display the value using eight digits with four digits to the right of the
decimal 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

20

2/18/2014

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 per

line 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-file

that enters two sets of values as vectors. These vectors are then
combined into a matrix, which is then dis-played as a table with
headings:

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);

21

2/18/2014

who and whos command


 At any point in a session, a list of all current variables can be

obtained by entering the who command:


>> who
Your variables are:
A
a
ans
b
x
 or, with more detail, enter the whos command:
>> whos
Name
Size
Bytes
Class
A
3x3
72
double array
a
1x5
40
double array
ans
1x1
8
double array
b
5x1
40
double array
x
1x1
16
double array (complex)
Grand total is 21 elements using 176 bytes

Thanks

22

You might also like