You are on page 1of 52

PROGRAMMING IN MATLAB

By
Dr. S. C. RANA

Book Suggested : Programming in MATLAB


by
Marc E. Herniter
IBSN 0-534-36880-8

General purpose commands


who
- List current variables.
whos
- List current variables, long form.
clear
- Clear all variables and functions from memory.
clear a b c Clears a, b and c variables from memory.
clear all - Clear all variables and functions from memory.
load
- Load workspace variables from disk.
Syntax

load filename
load (filename, variables)
save
- Save workspace variables to disk.
Syntax
save(filename)
save(filename, variables)
saveas
memory
quit
exit
cd
pwd
dir
ls

- Save Figure or model to desired output format.


- Help for memory limitations.
- Quit MATLAB session
- Exit from MATLAB.
Operating system commands.
- Change current working directory.
- Show (print) current working directory.
- List directory.
- List directory.

Matlab Movie and Matlab Movie to avi

Matlab movie (FM) is captured in the following way:


FM= getframe;
movie2avi(mov, filename, ParameterName,
ParameterValue)
movie2avi(Fm,'scrmov2','compression','Cinepak','fps',5,'qua
'compression
On UNIX operating systems, the only valid
lity',100);

value is 'None'. On Windows systems, valid values include:


'MSVC , 'RLE, 'Cinepak' on 32-bit systems.'Indeo3' or
'Indeo5' on 32-bit Windows XP systems. Default is 'Indeo5'
on Windows systems and
None' on UNIX systems.

'fps : A scalar value specifying the speed of the AVI movie in


frames per second (fps). Default is 15 fps.

'quality :

A number from 0 through 100. Higher quality


numbers result in higher video quality and larger file sizes.
Lower quality numbers result in lower video quality and smaller
file sizes. Valid only for compressed movies. Defult value is 75.
Related matlab code: scr_force_q_contournew

PROGRAMMING

Its a sequence of commands to


execute some
within
very short time
X calculation
+ y =25
To draw aagraph
2

y 25 x 2
In Matlab: code is circle.m
x1=0: 0.01: 5;
x2= 0: -0.01: -5;
y1=sqrt(25 - x1.^2);
plot(x1,y1, x1, -y1, x2, y1, x2, -y1)

ans
Predefined Variables.
Most recent answer
Description
The MATLAB software creates the ans variable automatically when you specify no output argument.
pi
Ratio of circle's circumference to its diameter
Description
pi returns the floating-point number nearest the value of .
eps
Floating-point relative accuracy
Description
eps returns the distance from 1.0 to the next largest double-precision number, that is eps = 2^(52).
Inf
Infinity
description
Inf returns the IEEE arithmetic representation for positive infinity. Infinity results from operations
like division by zero and overflow, which lead to results too large to represent as conventional
floating-point values.
NaN
Not-a-Number
Description
NaN returns the IEEE arithmetic representation for Not-a-Number (NaN). These result from
operations which have undefined numerical results.
1. Addition or subtraction, such as magnitude subtraction of infinities as (+Inf)+(-Inf);
2. Multiplication, such as 0*Inf;
3. Division, such as 0/0 and Inf/Inf
i or j
Imaginary unit
Example: a+bi and x+i*y .
Description
As the basic imaginary unit =sqrt(-1), i is used to enter complex numbers.

format
Set display format for output
Syntax
Format : by itself specifies the default display type, format short (that is, 5-digit scaled, fixed-point
values).
format type
Description
Use the format function to control the output format of numeric values displayed in the Command
Window.

Type

Result

format
short
(by default)

Scaled fixed-point format, with 4 digits after the decimal


point. e.g. 3.1416.

If you are displaying a matrix with a wide range of values, consider using short g. See Example 5.

Format long Scaled fixed-point format with 14 to 15 digits after the


decimal point for double; and 7 digits after the decimal point
for single. For example, 3.141592653589793.
format
short e

Floating-point format, with 4 digits after the decimal point.


For example, 3.1416e+000.

format
Long e

Floating-point format, with 14 to 15 digits after the decimal


point for double; and 7 digits after the decimal point for
single. For example, 3.141592653589793e+000.

format rat

Ratio of small integers. For example, 355/113

Defining Variables.
Variables are defined by typing a alpanumeric name of maximum 63 character long (along with
underscore) followed by
the equal sign and then a value or mathematical expression.
Example:
This_is_a_very_very_long_variable_name_of_largest_63_characters=90
var1=2*x^2 +3*x-2;
Defining Strings.
Syntax
S = 'Any Characters'
S = [S1 S2 ...] ; concatenates character arrays S1, S2, etc. into a new character array, S.
Examples
Create a simple string that includes a single quote.
msg = 'You''re right!'
msg = You're right!
Create the string name using two methods of concatenation.
name = ['Thomas' ' R. ' 'Lee']
name = strcat('Thomas',' R.',' Lee')
Create a character array of strings.
Create a cell array of strings.
S = {'Hello' 'Goodbye'; 'Yes' 'No'}
S = 'Hello' 'Goodbye'
'Yes'
'No
str2num
Convert string to number
Syntax
x = str2num('str')
num2str
Convert number to string
Syntax
str = num2str(A)

Debugging commands:
dbstop

- Set breakpoint.

dbclear

- Remove breakpoint.

dbcont

- Resume execution.

dbdown

- Change local workspace context.

dbmex

- Enable MEX-file debugging.

dbstack

- List who called whom.

dbstatus - List all breakpoints.


dbstep

- Execute one or more lines.

dbtype

- List M-file with line numbers.

dbup

- Change local workspace context.

dbquit

- Quit debug mode.

Matlab Commands
Arithmetic Operators
+, - , *, .*, /, ./, \, .\, ^, .^, , .
Matrix and array arithmetic
Syntax
A+B
A-B
A*B
A.*B - Element by element operation
A/B= simply right division or for matrix B*inv(A)
A./B- - Element by element operation
A\B = matrix left division= inv(A)*B
A.\B - Element by element operation
A^B
A.^B - Element by element operation
A= Matrix transpose. A is the linear algebraic transpose of
A.
A.= Array transpose. A.' is the array transpose of A.

Relational Operators <, > ,<=, >=,. ==, ~=


Relational operations
Syntax
A<B
A>B
A <= B
A >= B
A == B
A ~= B

{ } - Curly braces are used in cell array assignment statements.


( ) - Parentheses are used to indicate precedence in arithmetic expressions in
the usual way.
= Used in assignment statements.
' Matrix transpose
. Decimal point.
. Field access. S(m).f when S is a structure, accesses the contents of field f
of that structure.
Matlab code: scalarf_dynamicifeld.m
.( ) Dynamic Field access. S.(df) when S is a structure, accesses the contents
of dynamic field df
of that structure. Dynamic field names are defined at runtime.
.. Parent folder. See cd.
... Continuation. Three or more periods at the end of a line continue the
current function on the
next line
, Comma. Used to separate matrix subscripts and function arguments.
; Semicolon. Used inside brackets to end rows. Used after an expression or
statement to suppress printing
: Colon. Create vectors, array subscripting, and for loop iterations.
% Percent. The percent symbol denotes a comment;
%{ %} Percent-brace. The text enclosed within the %{ and %} symbols is a
comment block.
! Exclamation point. Indicates that the rest of the input line is issued as a
command to the operating system

colon (:)
Create vectors, array subscripting, and for-loop iterators
Description
The colon is one of the most useful operators in MATLAB. It can create vectors,
subscript arrays, and specify for iterations.
The colon operator uses the following rules to create regularly spaced vectors for scalar
values i, j, and k:
j:k is the same as [j,j+1,...,k], or empty when j > k.
j:i:k is the same as [j,j+i,j+2i, ...,j+m*i], where m = fix((k-j)/i), for integer values.
If you specify nonscalar arrays, MATLAB interprets j:i:k as j(1):i(1):k(1).
You can use the colon to create a vector of indices to select rows, columns, or elements
of arrays, where:
A(:,j) is all the elements in the jth column of A.
A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.
A(j:k) is A(j), A(j+1),...,A(k).
A(:,j:k) is A(:,j), A(:,j+1),...,A(:,k).

A(:,:,k) is the kth page of three-dimensional array A.


A(i,j,k,:) is a vector in four-dimensional array A. The vector includes A(i,j,k,1),
A(i,j,k,2), A(i,j,k,3), and so on.
A(:) is all the elements of A, regarded as a single column. On the left side of
an assignment statement, A(:) fills A, preserving its shape from before. In this
case, the right side must contain the same number of elements as A

Concatenation
Concatenation is the process of joining small matrices to
make bigger ones. In fact, you made your first matrix by
concatenating its individual elements. The pair of square
brackets, [], is the concatenation operator. For an
example, start with the 4-by-4 square matrix A, and form
B = [A, A+32; A+48, A+16]

A= [ 1 2 3 4; 2 3 4 5;3 4 5 6;4 5 6 7]

Trigonometric Function
cos(x)
cosd(x)
sin(x)
tan(x)
asin(x)
acos(x)
atan(x)
atan2(x,y)
sinh(x)
cosh(x)
tanh(x)
asinh(x)
acosh(x)
atanh(x)

sind(x) etc.

Exp (Exponential)
Syntax
Y = exp(X) when X is scalar
Examples
Find the value of :
y=exp(i*pi)

Expm (Matrix exponential)


Syntax
Y = expm(X) when X is matrix
Examples
This example computes and compares the matrix exponential of A and the
exponential of A.
A = [1 1 0; 0 0 2; 0 0 -1 ]; expm(A)

expm1
Compute exp(x)-1 accurately for small values of x
Syntax
y = expm1(x)

.
log
Natural logarithm

Continued
log10
Common (base 10) logarithm
Syntax
Y = log10(X)

log1p
Compute log(1+x) accurately for small values of x
Syntax
y = log1p(x)

.
sqrt
X
Square root,
Syntax
B = sqrt(X)

nthroot
n
X
Real nth root of real numbers,
Syntax
y = nthroot(X, n)

abs
Absolute value and complex magnitude
Syntax
abs(Z)
abs(-5) = 5 ; abs(3+4i) =
= 5;

.. 32 42
imag
Imaginary part of complex number,Z=3+4i
Syntax
Y = imag(Z) where Z=x+iy

real
Real part of complex number
Syntax
X = real(Z) where Z=x+iy

..
conj
Z xi y
Complex conjugale of Z=x+iy is
Syntax
ZC = conj(Z) where Z=x+iy

..
complex

Construct complex data from real and imaginary components


Syntax

angle
Phase angle
Syntax
P = angle(Z) ; for Z=x+iy,

1
P

tan
( y / x)

sign
Signum function
Syntax
Y = sign(X)
Description
Y = sign(X) returns an array Y the same size as X, where each element of Y is:
1 if the corresponding element of X is greater than zero
0 if the corresponding element of X equals zero
-1 if the corresponding element of X is less than zero
For nonzero complex X, sign(X) = X./abs(X).

..
find
Find indices and values of nonzero elements
Syntax
ind = find(X); Where ind is an array containing the location of non zero entries of X
[r,c,v]=find(X > 2); r= row, c=column, v=vector for logical array
[r,c,v]=find(X <2); r= row, c=column, v=vector for logical array
[r,c]=find(X >==0); r= row, c=column

Elementary matrices
zeros
Create array of all zeros
Syntax
B = zeros(n)
B = zeros(m,n)
ones
Create array of all ones
Syntax
Y = ones(n)
Y = ones(m,n)
eye
Identity matrix
Syntax
Y = eye(n)
Y = eye(m,n)
rand
Uniformly distributed random numbers
Syntax
r = rand(n)
rand(m,n)
randn
Normally distributed random numbers
Syntax
r = randn(n)
randn(m,n)

Basic Array information


size
Array dimensions
Syntax
d = size(X)
[m,n] = size(X)
length
Length of vector or largest array dimension
Syntax
Number Of Elements = length(array)
disp
Display text or array
Syntax
disp(X)
Description
disp(X) displays an array, without printing the array name. If X
contains a text string, the string is displayed.
sort
Sort array elements in ascending order
Syntax
B = sort(A)
Max
min
Largest elements in array
smallest elements in array
Syntax
Syntax
C = max(A)
C = min(A)

linspace
Generate linearly spaced vectors
Syntax
y = linspace(a,b,n)- generates a row vector y of n points linearly spaced
between and
including a and b.
logspace
Generate logarithmically spaced vectors
Syntax
y = logspace(a,b,n)- generates n points between 10^a and 10^b.
meshgrid
Generate X and Y arrays for 2-D or 3-D plots
Syntax
[X,Y] = meshgrid(x,y)-% where x,y has same size.
[X,Y] = meshgrid(x)
[X,Y,Z] = meshgrid(x,y,z)
Description
[X,Y] = meshgrid(x,y) transforms the domain specified by vectors x and
y into arrays X and Y, which can be used to evaluate functions of two
variables. The rows of the output array X are copies of the vector x;
columns of the output array Y are copies of the vector y.

linspace
Generate linearly spaced vectors
Syntax
y = linspace(a,b,n)- generates a row vector y of n points linearly spaced
between and
including a and b.
logspace
Generate logarithmically spaced vectors
Syntax
y = logspace(a,b,n)- generates n points between 10^a and 10^b.
meshgrid
Generate X and Y arrays for 2-D or 3-D plots
Syntax
[X,Y] = meshgrid(x,y)-% where x,y has same size.
[X,Y] = meshgrid(x)
[X,Y,Z] = meshgrid(x,y,z)
Description
[X,Y] = meshgrid(x,y) transforms the domain specified by vectors x and
y into arrays X and Y, which can be used to evaluate functions of two
variables. The rows of the output array X are copies of the vector x;
columns of the output array Y are copies of the vector y.

Continued
diag
Diagonal matrices and diagonals of matrix
Syntax
X = diag(v,k)
X = diag(v)
v = diag(X,k)
v = diag(X)
Description
X = diag(v,k) when v is a vector of n components, returns a square
matrix X of order n+abs(k), with the elements of v on the kth
diagonal. k = 0 represents the main diagonal, k > 0 above the main
diagonal, and k < 0 below the main diagonal.
X = diag(v) puts v on the main diagonal, same as above with k = 0.
v = diag(X,k) for matrix X, returns a column vector v formed from
the elements of the kth diagonal of X.
v = diag(X) returns the main diagonal of X, same as above with k =
0.
imagesc
Scale data and display image object
Syntax
imagesc(C)

blkdiag
Construct block diagonal matrix from input arguments
Syntax
out = blkdiag(a,b,c,d,...)
Description
out = blkdiag(a,b,c,d,...), where a, b, c, d, ... are matrices, outputs a
block diagonal matrix of the form [a 0 0 00;0 b 0 00;0 0 c 00;0
0 0 d 00]
The input matrices do not have to be square, nor do they have to be
of equal size.
tril
Lower triangular part of matrix
Syntax
L = tril(X)
L= tril(X,k)
triu
Upper triangular part of matrix
Syntax
U = triu(X)
U = triu(X,k); returns the element on and above the kth diagonal of
X. k = 0 is the main diagonal, k > 0 is above the main diagonal, and
k < 0 is below the main diagonal.

floor
Some Rounding function
Round toward negative infinity
Syntax
B = floor(A)
Description
B = floor(A) rounds the elements of A to the nearest integers less than or
equal to A. For complex A, the imaginary and real parts are rounded
independently.
round
Round to nearest integer
Syntax
Y = round(X)
Description
Y = round(X) rounds the elements of X to the nearest integers. For complex X,
the imaginary and real parts are rounded independently.
fix
Round toward zero
Syntax
B = fix(A)
Description
B = fix(A) rounds the elements of A toward zero, resulting in an array of
integers. For complex A, the imaginary and real parts are rounded
independently.
ceil
Round toward positive infinity
Syntax
B = ceil(A)
Description

Linear Alzebra
Related matlab code: blockdiag.m

det
Matrix determinant
Syntax
d = det(X)
Description
d = det(X) returns the determinant of the square matrix X.
trace
Sum of diagonal elements
Syntax
b = trace(A)
Description
b = trace(A) is the sum of the diagonal elements of the matrix A.
inv
Matrix inverse
Syntax
Y = inv(X)
Description
Y = inv(X) returns the inverse of the square matrix X. A warning
message is printed if X is badly scaled or nearly singular.
eig /eigs
eig gives Eigenvalues and eigenvectors; eigs gives maximum
eigenvalue .
Syntax

Continued
svd
Singular value decomposition
Syntax
[U,S,V] = svd(X)
[U,S,V] = svd(X,0)
Description
The svd command computes the matrix singular value
decomposition.
s = svd(X) returns a vector of singular values.
[U,S,V] = svd(X) produces a diagonal matrix S of the same
dimension as X, with nonnegative diagonal elements in decreasing
order, and unitary matrices U and V so that X = U*S*V'.
mod
Modulus after division
Syntax
M = mod(X,Y)
Description
M = mod(X,Y) if Y ~= 0, returns X - n.*Y where n = floor(X./Y). If Y is
not an integer and the quotient X./Y is within roundoff error of an
integer, then n is that integer. The inputs X and Y must be real arrays
of the same size, or real scalars.
The following are true by convention:

norm
Vector and matrix norms
Syntax
n = norm(A)
n = norm(A, p)
Description
The norm of a matrix is a scalar that gives some measure of the
magnitude of the elements of the matrix. The norm function
calculates several different types of matrix norms:
n = norm(A) returns the largest singular value of A, max(svd(A)).
n = norm(A,p) returns a different kind of norm, depending on the
value of p.
If p is...
1
The 1-norm, or largest column sum of A, max(sum(abs(A))).
2
The largest singular value (same as norm(A)).
inf
The infinity norm, or largest row sum of A, max(sum(abs(A'))).
'fro'
The Frobenius-norm of matrix A, sqrt(sum(diag(A'*A))).

plot
2-D line plot
Syntax
plot(Y)
plot(X1,Y1,.,Xn,Yn)
plot(X1,Y1,LineSpec,....,Xn,Yn,LineSpec)
plot(X1,Y1,LineSpec,'PropertyName',PropertyValue)
Example
plot(x,y,'--rs','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor
','g',... 'MarkerSize',10)
Line Style with specier
Specifie Line Style
r
Related code:
sketch.m

Solid line
(default)

--

Dashed line

Dotted line

-.

Dash-dot line

Marker type with Specifiers


Specifier

Marker Type

Plus sign

Asterisk

Circle

point

Square

Cross

Diamond

Upward-pointing
triangle

Downward-pointing
triangle

<

left-pointing triangle

>

Right-pointing triangle

Pentagon

Specifier

Color
Specifiers

Colour

Red

Green

Blue

Cyan

Magenta

Yellow

Black

white

Plotting Data Points with No Line


If you specify a marker, but not a line style, only the markers are plotted.
For example:
plot(x,y,'d')
axis
Axis scaling and appearance
Syntax
axis([xmin xmax ymin ymax])

xlabel, ylabel, zlabel


Label x-, y-, and z-axis
Syntax
xlabel('string')
xlabel(...,'PropertyName',PropertyValue,...)
Example:
ylabel('George''s Popularity','fontsize',12,'fontweight','b')
title
Add title to current axes
Syntax
title('string')
title(...,'PropertyName',PropertyValue,...)
plotyy
2-D line plots with y-axes on both left and right side
Syntax
plotyy(X1,Y1,X2,Y2)
semilogx, semilogy
Semilogarithmic plots
Syntax
semilogx(X1,Y1,...)
semilogx(X1,Y1,LineSpec,...)
loglog
Log-log scale plot
Syntax
loglog(X1,Y1,...)

contour
Contour plot of matrix
Syntax
contour(X,Y,Z,[v v]); draw contour plots of Z using X and Y to determine the
x- and yaxis limits. No of contour level= size of vec tor v
clabel
Contour plot elevation labels
Syntax
clabel(C)
Example
v1=[4;3;2;1;0.5];
C=contour(x,y,q5,[v1 v1]); clabel(C); hold; contour(x,y,Z5,[0 0])
quiver
Quiver or velocity plot
Syntax
quiver(x,y,u,v); plots vectors as arrows at the coordinates specified in each
corresponding pair of
elements in x and y. The matrices x, y, u, and v must all be
the same size and
contain corresponding position and velocity components.
streamline
Plot streamlines from 2-D or 3-D vector data
Syntax

subplot
(Related matlab code: RK4tutorial.m)
Description
subplot divides the current figure into rectangular panes that are
numbered rowwise. Each pane contains an axes object which you can
manipulate using Axes Properties. Subsequent plots are output to the
current pane.
fopen
Open file, or obtain information about open files
Syntax
fid1 = fopen(filename)
fid2 = fopen(filename, permission)
'r :Open file for reading (default).
'w :Open or create new file for writing. Discard existing contents, if any.
'a:Open or create new file for writing. Append data to the end of the file.
'r+ :Open file for reading and writing.
'w+ :Open or create new file for reading and writing. Discard existing
contents, if any.
'a+:Open or create new file for reading and writing. Append data to the
end of the file.
'A:Append without automatic flushing. (Used with tape drives.)
fprintf
Write data to text file
Syntax

For execution of loop


for
Execute statements specified number of times
Syntax
for index = values
program statements :
end
while
Repeatedly execute statements while condition is true
Syntax
while expression
program statements :
end
if
Execute statements if condition is true
Syntax
if expression, statements, end
if expression1 statements1
elseif expression2 statements2
else statements3
end

function
Declare function
Syntax
function [out1, out2, ...] = myfun(in1, in2, ...)
Description
function [out1, out2, ...] = myfun(in1, in2, ...) declares the function
myfun, and its inputs and outputs. The function declaration must be
the first executable line of any MATLAB function.
The existing commands and functions that compose the new
function reside in a text file that has a .m extension to its filename.
MATLAB program files can be either scripts or functions. Scripts are
simply files containing a sequence of MATLAB statements. Functions
make use of their own local variables and accept input arguments.
The name of a MATLAB function file begins with an alphabetic
character and has a filename extension of .m. The file name, less its
extension, is what MATLAB searches for when you try to use the
script or function.
The first line of a function defines the syntax with which you call it.
The name you give to a function, as defined in the first line, should
be the same as the name of the file containing the function, but
without the .m extension.

Fixed point algorithm


Definition1: A fixed point of a function g(x) is a real
number P such that P = g(P).
Geometrically, the fixed points of a function y = g(x)
are the points of intersection of y = g(x) and y = x.
Definition 2.
The iteration Pn+1 = g(Pn) for n = 0, 1, ... is
called fixed
point iteration

Numerical Integration

q = integral(fun handle,xmin,xmax)integral(@(x) sin(x),0,pi)


e.g.
sum1=integral2(@(x,y) 0.3*x.*y,0,2.5,0,2)
integral2(fun handle,xmin,xmax,ymin,ymax)
q = integral3(fun
handle,xmin,xmax,ymin,ymax,zmin,zmax)
fun = @(x,y,z) y.*sin(x)
+z.*cos(x);
q=
integral3(fun,0,pi,0,1,-1,1)
Alternative, if you have numerical value of function at each of the nodes
of your grid,
Integration= The function value *dx ; sum all the integrations at the
nodes. % 1-d
Integration= The function value *dx*dy ; sum all the integrations at the
nodes. % for 2-d
Integration= The function value *dx *dy*dz; sum all the integrations at
the nodes. % 3-d Here , quadrilateral rule for integration has been
adopted.

R-K4 method for time marching


t=0; dt=0.01; % dt is any time step.
Y0= y0; % yo is the vaue of variable y at
time, t=0;
F=f(Y0); % Say , f(y)= 5y and y =g(t)
t=t + dt;
K1= F*dt;
Y1= Y0+0.5K1; F=f(Y1);
Related code:
K2=F* dt;
RK4tutorial.m
and
Y1=Y0+0.5K2; F=f(Y1);
BLASIUS.m
K3=F*dt;
y
Y1=Y0+K3; F=f(Y1)
K4=F*dt;
Y1=Y0+(K1+2K2+2K3+K4)/6; % Y1 is value
U
writeofRy at
K 4t=t+dt
code for the following ODEs
U
Y0=Y1;

dy
5 y when t 0, y 5, upto t 5
( y)
dt
2.
2 f ( ) f ( ) f ( ) 0 with BC as
at 0 : f ( ) 0, f ( ) 0 and at , f ( ) 1
(Originaly, at y 0 : u 0, v 0 and at y , u U )

1.

Finite Difference Method


Forward Difference,

u ui1, j ui , j
=
x
x

and

u ui, j 1 ui, j
=
y
y

u ui , j ui1, j
u ui , j ui , j 1
=
and
=
x
x
y
y
u ui 1, j ui 1, j
u ui1, j ui 1, j
Central Difference,
=
and
=
x
2x
y
2y
Backward Difference,

2u ui2, j 2ui1, j ui, j


Forward Difference,
=
x 2
x2
2u ui, j 2 2ui, j1 ui, j
and
=
y 2
y 2
2u ui, j 2ui1, j ui2, j
Backward Difference,

x2
x2
2u u 2u u

i, j
i , j 1
i , j 2
and
=
2
y
y 2
2u u

i 1, j 2ui , j ui 1, j
Central Difference,
=
x 2
x2
2u u

i , j 1 2ui , j ui , j 1
and
=
y 2
y 2

Matlab code: scr19.m

Matlab code:
scr20.m

Matlab code:
scr18.m

1
n 1
n 1
n
BTi n1,
ATi
j DTi , j
1, j Ci

0
0

0
0

.
0

0
0

0
D
B
0
0
.
.
.
.
0

0
A
D
B
0
0
0
0
0
0

0
0
A
D
B
0
0
0
0
0

.
.
0
A
D
B
0
0
0
0

0 0 0

0 d 22 a23 0
0 0 d' a
33 34

0
.

0
0

.
.
.
0
A
.
.
0
.
.

.
.
.
.
0
A
.
.
0
.

.
.
.
.
.
0
A
.
B
0

T1, j

T2, j

T
3, j
0

T4, j
.

.
.

.
.

0
.

0
TN 1, j

A
T

N
,
j

1 ( N 1) X ( N 1)

0
0
0
.
.
.
0
A
D
0

T
N 1, j

.
.

. . .
. . .

0
.

. . .

'
d44
a45
0
.
0 0
.
0
.
.

0
.
.
.
.

0
0
.
.
.

0
.
.
0
0

.
0
.
.
0

.
.
.
.
0
.
.
0
. aN 1, N

. 0 0

'
d NN

. . .

n1

C4, j

.
.
.

1 N 1XN 1

c '(k ) c (k )

N 1,1

n1

c(k 1)b(k )
d '( k 1)
a (k 1)b(k )
d '(k ) d (k )
d '( k 1)

N 1, j
C

N, j
1

( N 1,1)

T1

T2
T3

T4
T5

aN , N 1

C2, j

C
3, j

0
0
0
.
.
.
.
.

C
2

C'
3

C'

.
.

TN 1
T
N
TN 1

.
.

.

.
CK

N 1X1 1

Back
substitution:
c(i) a(i).T (i 1)

T (i )

d (i, i)

Matlab code:
scr17.m

You might also like