Numerical Methods in Engineering With MATLAB - 2005 (2) - 10-36 PDF
Numerical Methods in Engineering With MATLAB - 2005 (2) - 10-36 PDF
Numerical Methods in Engineering With MATLAB - 2005 (2) - 10-36 PDF
r MATLAB contains a large number of functions that access proven numerical li-
braries, such as LINPACK and EISPACK. This means that many common tasks (e.g.,
solution of simultaneous equations) can be accomplished with a single function
call.
r There is extensive graphics support that allows the results of computations to be
plotted with a few statements.
r All numerical objects are treated as double-precision arrays. Thus there is no need
to declare data types and carry out type conversions.
1
2 Introduction to MATLAB
The syntax of MATLAB resembles that of FORTRAN. To get an idea of the similari-
ties, let us compare the codes written in the two languages for solution of simultaneous
equations Ax = b by Gauss elimination. Here is the subroutine in FORTRAN 90:
subroutine gauss(A,b,n)
use prec_ mod
implicit none
real(DP), dimension(:,:), intent(in out) :: A
real(DP), dimension(:), intent(in out) :: b
integer, intent(in) :: n
real(DP) :: lambda
integer :: i,k
! --------------Elimination phase--------------
do k = 1,n-1
do i = k+1,n
if(A(i,k) /= 0) then
lambda = A(i,k)/A(k,k)
A(i,k+1:n) = A(i,k+1:n) - lambda*A(k,k+1:n)
b(i) = b(i) - lambda*b(k)
end if
end do
end do
! ------------Back substitution phase----------
do k = n,1,-1
b(k) = (b(k) - sum(A(k,k+1:n)*b(k+1:n)))/A(k,k)
end do
return
end subroutine gauss
The statement use prec mod tells the compiler to load the module prec mod
(not shown here), which defines the word length DP for floating-point numbers. Also
note the use of array sections, such as a(k,k+1:n), a feature that was not available
in previous versions of FORTRAN.
The equivalent MATLAB function is (MATLAB does not have subroutines):
function b = gauss(A,b)
n = length(b);
%-----------------Elimination phase-------------
for k = 1:n-1
for i = k+1:n
3 1.1 General Information
if A(i,k) ˜= 0
lambda = A(i,k)/A(k,k);
A(i,k+1:n) = A(i,k+1:n) - lambda*A(k,k+1:n);
b(i)= b(i) - lambda*b(k);
end
end
end
%--------------Back substitution phase-----------
for k = n:-1:1
b(k) = (b(k) - A(k,k+1:n)*b(k+1:n))/A(k,k);
end
Simultaneous equations can also be solved in MATLAB with the simple command
A\b (see below).
MATLAB can be operated in the interactive mode through its command window,
where each command is executed immediately upon its entry. In this mode MATLAB
acts like an electronic calculator. Here is an example of an interactive session for the
solution of simultaneous equations:
The symbol >> is MATLAB’s prompt for input. The percent sign (%) marks the
beginning of a comment. A semicolon (;) has two functions: it suppresses printout
of intermediate results and separates the rows of a matrix. Without a terminating
semicolon, the result of a command would be displayed. For example, omission of
the last semicolon in the line defining the matrix A would result in
>> A = [2 1 0; -1 2 2; 0 1 4]
A =
2 1 0
-1 2 2
0 1 4
4 Introduction to MATLAB
Functions and programs can be created with the MATLAB editor/debugger and
saved with the .m extension (MATLAB calls them M-files). The file name of a saved
function should be identical to the name of the function. For example, if the function
for Gauss elimination listed above is saved as gauss.m, it can be called just like any
MATLAB function:
>> A = [2 1 0; -1 2 2; 0 1 4];
>> b = [1; 2; 3];
>> soln = gauss(A,b)
soln =
0.2500
0.5000
0.6250
Variables
Variable names, which must start with a letter, are case sensitive. Hence xstart and
xStart represent two different variables. The length of the name is unlimited, but
only the first N characters are significant. To find N for your installation of MATLAB,
use the command namelengthmax:
>> namelengthmax
ans =
63
Variables that are defined within a MATLAB function are local in their scope.
They are not available to other parts of the program and do not remain in memory
after exiting the function (this applies to most programming languages). However,
variables can be shared between a function and the calling program if they are declared
global. For example, by placing the statement global X Y in a function as well as
the calling program, the variables X and Y are shared between the two program units.
The recommended practice is to use capital letters for global variables.
MATLAB contains several built-in constants and special variables, most important
of which are
inf Infinity
NaN Not a number
√
i or j −1
pi π
realmin Smallest usable positive number
realmax Largest usable positive number
>> 0/0
6 Introduction to MATLAB
ans =
NaN
>> eps
ans =
2.2204e-016
Arrays
Arrays can be created in several ways. One of them is to type the elements of the array
between brackets. The elements in each row must be separated by blanks or commas.
Here is an example of generating a 3 × 3 matrix:
>> A = [ 2 -1 0
-1 2 -1
0 -1 1]
A =
2 -1 0
-1 2 -1
0 -1 1
The elements can also be typed on a single line, separating the rows with semi-
colons:
>> A = [2 -1 0; -1 2 -1; 0 -1 1]
A =
2 -1 0
-1 2 -1
0 -1 1
Unlike most computer languages, MATLAB differentiates between row and col-
umn vectors (this peculiarity is a frequent source of programming and input errors).
For example,
7 1.2 Data Types and Variables
The single quote (’) is the transpose operator in MATLAB; thus b’ is the transpose
of b.
The elements of a matrix, such as
⎡ ⎤
A11 A12 A13
⎢ ⎥
A = ⎣ A21 A22 A23 ⎦
A31 A32 A33
can be accessed with the statement A(i,j), where i and j are the row and column
numbers, respectively. A section of an array can be extracted by the use of colon
notation. Here is an illustration:
>> A = [8 1 6; 3 5 7; 4 9 2]
A =
8 1 6
3 5 7
4 9 2
ans =
1
5
9
Array elements can also be accessed with a single index. Thus A(i) extracts the
ithelement of A, counting the elements down the columns. For example, A(7) and
A(1,3) would extract the same element from a 3 × 3 matrix.
Cells
A cell array is a sequence of arbitrary objects. Cell arrays can be created by enclosing
their contents between braces {}. For example, a cell array c consisting of three cells
can be created by
As seen above, the contents of some cells are not printed in order to save space.
If all contents are to be displayed, use the celldisp command:
>> celldisp(c)
c{ 1} =
1 2 3
c{ 2} =
one two three
c{ 3} =
6.0000 + 7.0000i
Strings
A string is a sequence of characters; it is treated by MATLAB as a character array. Strings
are created by enclosing the characters between single quotes. They are concatenated
with the function strcat, whereas a colon operator (:) is used to extract a portion of
the string. For example,
1.3 Operators
Arithmetic Operators
MATLAB supports the usual arithmetic operators:
+ Addition
− Subtraction
∗ Multiplication
ˆ Exponentiation
When applied to matrices, they perform the familiar matrix operations, as illus-
trated below.
ans =
8 10 12
4 6 8
/ Right division
\ Left division
If a and b are scalars, the right division a/b results in a divided by b, whereas the left
division is equivalent to b/a. In the case where A and B are matrices, A/B returns the
solution of X*A = B and A\B yields the solution of A*X = B.
Often we need to apply the *, / and ˆ operations to matrices in an element-by-
element fashion. This can be done by preceding the operator with a period (.) as
follows:
.* Element-wise multiplication
./ Element-wise division
.ˆ Element-wise exponentiation
Comparison Operators
The comparison (relational) operators return 1 for true and 0 for false. These operators
are
The comparison operators always act element-wise on matrices; hence they result in
a matrix of logical type. For example,
Logical Operators
The logical operators in MATLAB are
& AND
| OR
˜ NOT
if condition
block
end
executes the block of statements if the condition is true. If the condition is false,
the block skipped. The if conditional can be followed by any number of elseif
constructs:
if condition
block
elseif condition
block
..
.
end
..
.
else
block
end
can be used to define the block of statements which are to be executed if none of
the if-elseif clauses are true. The function signum below illustrates the use of the
conditionals.
sgn = 0;
end
switch
The switch construct is
switch expression
case value1
block
case value2
block
..
.
otherwise
block
end
Here the expression is evaluated and the control is passed to the case that matches the
value. For instance, if the value of expression is equal to value2, the block of statements
following case value2 is executed. If the value of expression does not match any
of the case values, the control passes to the optional otherwise block. Here is an
example:
function y = trig(func,x)
switch func
case ’sin’
y = sin(x);
case ’cos’
y = cos(x);
case ’tan’
y = tan(x);
otherwise
error(’No such function defined’)
end
>> trig(’tan’,pi/3)
ans =
1.7321
14 Introduction to MATLAB
Loops
while
The while construct
while condition:
block
end
executes a block of statements if the condition is true. After execution of the block,
condition is evaluated again. If it is still true, the block is executed again. This process
is continued until the condition becomes false.
The following example computes the number of years it takes for a $1000 principal
to grow to $10,000 at 6% annual interest.
for
The for loop requires a target and a sequence over which the target loops. The form
of the construct is
>> n = 0:5;
>> y = cos(n*pi/10)
y =
1.0000 0.9511 0.8090 0.5878 0.3090 0.0000
break
Any loop can be terminated by the break statement. Upon encountering a break
statement, the control is passed to the first statement outside the loop. In the fol-
lowing example the function buildvec constructs a row vector of arbitrary length
by prompting for its elements. The process is terminated when an empty element is
encountered.
function x = buildvec
for i = 1:1000
elem = input(’==> ’); % Prompts for input of element
if isempty(elem) % Check for empty element
break
end
x(i) = elem;
end
>> x = buildvec
==> 3
==> 5
==> 7
==> 2
==>
x =
3 5 7 2
continue
When the continue statement is encountered in a loop, the control is passed to
the next iteration without executing the statements in the current iteration. As an
illustration, consider the following function that strips all the blanks from the string s1:
function s2 = strip(s1)
s2 = ’’; % Create an empty string
for i = 1:length(s1)
16 Introduction to MATLAB
if s1(i) == ’ ’
continue
else
s2 = strcat(s2,s1(i)); % Concatenation
end
end
return
A function normally returns to the calling program when it runs out of statements.
However, the function can be forced to exit with the return command. In the ex-
ample below, the function solve uses the Newton–Raphson method to find the zero
of f (x) = sin x − 0.5x. The input x (guess of the solution) is refined in successive
iterations using the formula x ← x + x, where x = − f (x)/ f (x), until the change
x becomes sufficiently small. The procedure is then terminated with the return
statement. The for loop assures that the number of iterations does not exceed 30,
which should be more than enough for convergence.
function x = solve(x)
for numIter = 1:30
dx = -(sin(x) - 0.5*x)/(cos(x) - 0.5); % -f(x)/f’(x)
x = x + dx;
if abs(dx) < 1.0e-6 % Check for convergence
return
end
end
error(’Too many iterations’)
>> x = solve(2)
x =
1.8955
error
Execution of a program can be terminated and a message displayed with the error
function
error(’message’)
For example, the following program lines determine the dimensions of a matrix and
aborts the program if the dimensions are not equal.
17 1.5 Functions
1.5 Functions
Function Definition
The body of a function must be preceded by the function definition line
The input and output arguments must be separated by commas. The number of
arguments may be zero. If there is only one output argument, the enclosing brackets
may be omitted.
To make the function accessible to other programs units, it must be saved under
the file name function name.m. This file may contain other functions, called subfunc-
tions. The subfunctions can be called only by the primary function function name or
other subfunctions in the file; they are not accessible to other program units.
Calling Functions
A function may be called with fewer arguments than appear in the function defini-
tion. The number of input and output arguments used in the function call can be
determined by the functions nargin and nargout, respectively. The following exam-
ple shows a modified version of the function solve that involves two input and two
output arguments. The error tolerance epsilon is an optional input that may be used
to override the default value 1.0e-6. The output argument numIter, which contains
the number of iterations, may also be omitted from the function call.
end
error(’Too many iterations’)
Evaluating Functions
Let us consider a slightly different version of the function solve shown below. The
expression for dx, namely x = − f (x)/ f (x), is now coded in the function myfunc,
so that solve contains a call to myfunc. This will work fine, provided that myfunc is
stored under the file name myfunc.m so that MATLAB can find it.
function y = myfunc(x)
y = -(sin(x) - 0.5*x)/(cos(x) - 0.5);
>> x = solve(2)
x =
1.8955
19 1.5 Functions
In the above version of solve the function returning dx is stuck with the name
myfunc. If myfunc is replaced with another function name, solve will not work unless
the corresponding change is made in its code. In general, it is not a good idea to alter
computer code that has been tested and debugged; all data should be communicated
to a function through its arguments. MATLAB makes this possible by passing the
function handle of myfunc to solve as an argument, as illustrated below.
It is now possible to use solve to find a zero of any f (x) by coding the function
x = − f (x)/ f (x) and passing its handle to solve.
In-Line Functions
If the function is not overly complicated, it can also be represented as an inline
object:
where expression specifies the function and var1, var2, . . . are the names of the inde-
pendent variables. Here is an example:
>> myfunc = inline (’xˆ2 + yˆ2’,’x’,’y’);
>> myfunc (3,5)
ans =
34
20 Introduction to MATLAB
1.6 Input/Output
Reading Input
The MATLAB function for receiving user input is
value = input(’prompt ’)
It displays a prompt and then waits for input. If the input is an expression, it is evalu-
ated and returned in value. The following two samples illustrate the use of input:
Printing Output
As mentioned before, the result of a statement is printed if the statement does not end
with a semicolon. This is the easiest way of displaying results in MATLAB. Normally
MATLAB displays numerical results with about five digits, but this can be changed
with the format command:
fprintf(’format ’, list )
where format contains formatting specifications and list is the list of items to be
printed, separated by commas. Typically used formatting specifications are
21 1.7 Array Manipulation
where w is the width of the field and d is the number of digits after the decimal point.
Line break is forced by the newline character. The following example prints a formatted
table of sin x vs. x at intervals of 0.2:
>> x = 0:0.2:1;
>> for i = 1:length(x)
fprintf(’%4.1f %11.6f\n’,x(i),sin(x(i)))
end
0.0 0.000000
0.2 0.198669
0.4 0.389418
0.6 0.564642
0.8 0.717356
1.0 0.841471
Colon Operator
Arrays with equally spaced elements can also be constructed with the colon operator.
For example,
>> x = 0:0.25:1
x =
0 0.2500 0.5000 0.7500 1.0000
22 Introduction to MATLAB
linspace
Another means of creating an array with equally spaced elements is the linspace
function. The statement
creates an array of n elements starting with xfirst and ending with xlast. Here is an
illustration:
>> x = linspace(0,1,5)
x =
0 0.2500 0.5000 0.7500 1.0000
logspace
The function logspace is the logarithmic counterpart of linspace. The call
zeros
The function call
X = zeros(m,n)
returns a matrix of m rows and n columns that is filled with zeroes. When the fun-
ction is called with a single argument, e.g., zeros(n), a n × n matrix is created.
ones
X = ones(m,n)
The function ones works in the manner as zeros, but fills the matrix with ones.
rand
X = rand(m,n)
This function returns a matrix filled with random numbers between 0 and 1.
23 1.7 Array Manipulation
eye
The function eye
X = eye(n)
Array Functions
There are numerous array functions in MATLAB that perform matrix operations and
other useful tasks. Here are a few basic functions:
length
The length n (number of elements) of a vector x can be determined with the function
length:
n = length(x)
size
If the function size is called with a single input argument:
[m,n] = size(X )
m = size(X ,dim)
it returns the length of X in the specified dimension (dim = 1 yields the number of
rows, and dim = 2 gives the number of columns).
reshape
The reshape function is used to rearrange the elements of a matrix. The call
Y = reshape(X ,m,n)
returns a m ×n matrix the elements of which are taken from matrix X in the column-
wise order. The total number of elements in X must be equal to m× n. Here is an
example:
24 Introduction to MATLAB
>> a = 1:2:11
a =
1 3 5 7 9 11
>> A = reshape(a,2,3)
A =
1 5 9
3 7 11
dot
a = dot(x,y )
This function returns the dot product of two vectors x and y which must be of the
same length.
prod
a = prod(x)
For a vector x, prod(x) returns the product of its elements. If x is a matrix, then a is a
row vector containing the products over each column. For example,
>> a = [1 2 3 4 5 6];
>> A = reshape(a,2,3)
A =
1 3 5
2 4 6
>> prod(a)
ans =
720
>> prod(A)
ans =
2 12 30
sum
a = sum(x)
This function is similar to prod, except that it returns the sum of the elements.
25 1.8 Writing and Running Programs
cross
c = cross(a,b)
The function cross computes the cross product: c = a × b, where vectors a and b
must be of length 3.
MATLAB has two windows available for typing program lines: the command window
and the editor/debugger. The command window is always in the interactive mode, so
that any statement entered into the window is immediately processed. The interactive
mode is a good way to experiment with the language and try out programming ideas.
MATLAB opens the editor window when a new M-file is created, or an existing file
is opened. The editor window is used to type and save programs (called script files in
MATLAB) and functions. One could also use a text editor to enter program lines, but
the MATLAB editor has MATLAB-specific features, such as color coding and automatic
indentation, that make work easier. Before a program or function can be executed, it
must be saved as a MATLAB M-file (recall that these files have the .m extension). A
program can be run by invoking the run command from the editor’s debug menu.
When a function is called for the first time during a program run, it is compiled
into P-code (pseudo-code) to speed up execution in subsequent calls to the function.
One can also create the P-code of a function and save it on disk by issuing the command
MATLAB will then load the P-code (which has the .p extension) into the memory
rather than the text file.
The variables created during a MATLAB session are saved in the MATLAB
workspace until they are cleared. Listing of the saved variables can be displayed by the
command who. If greater detail about the variables is required, type whos. Variables
can be cleared from the workspace with the command
clear a b . . .
which clears the variables a, b, . . . . If the list of variables is omitted, all variables are
cleared.
26 Introduction to MATLAB
1.9 Plotting
MATLAB has extensive plotting capabilities. Here we illustrate some basic commands
for two-dimensional plots. The example below plots sin x and cos x on the same plot.
The plots appearing in this book from here on were not produced by MATLAB.
We used the copy/paste operation to transfer the numerical data to a spreadsheet
and then let the spreadsheet create the plot. This resulted in plots more suited for
publication.