0% found this document useful (0 votes)
25 views

Programming in Matlab

The document provides an overview of basic MATLAB commands for programming and debugging. It discusses general purpose commands like who, whos, clear, load, save. It also covers operating system commands like cd, dir, ls and movie conversion commands. Defining variables, strings, data types and predefined variables are described. Formatting output and debugging commands like dbstop, dbclear are summarized. Finally, basic MATLAB operators, special characters and colon operator usage are outlined.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Programming in Matlab

The document provides an overview of basic MATLAB commands for programming and debugging. It discusses general purpose commands like who, whos, clear, load, save. It also covers operating system commands like cd, dir, ls and movie conversion commands. Defining variables, strings, data types and predefined variables are described. Formatting output and debugging commands like dbstop, dbclear are summarized. Finally, basic MATLAB operators, special characters and colon operator usage are outlined.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 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 - Save Figure or model to desired output format.


memory - Help for memory limitations.
quit - Quit MATLAB session
exit - Exit from MATLAB.
Operating system commands.
cd - Change current working directory.
pwd - Show (print) current working directory.
dir - List directory.
ls - 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,'quality',100);

• 'compression‘ On UNIX operating systems, the only valid 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

It’s a sequence of commands to execute some


calculation within a very short time
X2 + y2 =25 To draw a graph

y   25  x2
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.
Realmin= 2^(-1022) or about 2.2251e-308. and realmax= 21024 or about 1.7977e+308.
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 Scaled fixed-point format, with 4 digits after the decimal point. e.g. 3.1416.
(by default)
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
Special Characters [ ] ( ) {} = ' . ... , ; : % !
[ ] - Brackets are used to form vectors and matrices. (examples)
{ } - 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) sind(x) etc.

tan(x)
asin(x)
acos(x)
atan(x)
atan2(x,y)
sinh(x)
cosh(x)
tanh(x)
asinh(x)
acosh(x)
atanh(x)
Exponential and logarithmic functions
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
Syntax
Y = log(X)
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
Square root, X
Syntax
B = sqrt(X)
………………………………………………………………………………………………………………………………………
nthroot
Real nth root of real numbers, n X
Syntax
y = nthroot(X, n)
Complex Functions
abs
Absolute value and complex magnitude
Syntax
abs(Z)
abs(-5) = 5 ; abs(3+4i) = 32  42 = 5 ;
……………………………………………………………………………………………………………………………………………..
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
Complex conjugale of Z=x+iy is Z  x i y
Syntax
ZC = conj(Z) where Z=x+iy
……………………………………………………………………………………………………………………………………………………..
complex
Construct complex data from real and imaginary components
Syntax
c = complex(a,b) ( i.e.= a+ib)
Continued
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.
Related matlab code: mesh.m
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.
Related matlab code: mesh.m
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 0…0;0 b 0 0…0;0 0 c 0…0;0 0 0 d 0…0]
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
B = ceil(A) rounds the elements of A to the nearest integers greater than or equal to A. For
complex A, the imaginary and real parts are rounded independently.
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
d = eig(A); [V,D] = eig(A) ; d = eigs(A); [V,D] = eigs(A)
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:
mod(X,0) is X
mod(X,X) is 0 Related matlab code is: SCR_FORCE_q_CONTOURnew.m
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
Specifier Line Style

Related code: sketch.m - Solid line (default)

-- Dashed line
: Dotted line

-. Dash-dot line
Marker type with Specifiers

Specifier Marker Type


+ Plus sign
* Asterisk
o Circle
. point
s Square
X Cross
d Diamond
^ Upward-pointing triangle
V Downward-pointing triangle

< left-pointing triangle


> Right-pointing triangle

P Pentagon
h Hexagon
Color Specifiers
Specifier Colour
r Red
g Green
B Blue
C Cyan
M Magenta
Y Yellow
K Black
w 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 y-
axis 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
streamline(X,Y,U,V,startx,starty) :Daws streamlines from 2-D vector data U, V. The arrays X, Y
define the coordinates for U, V and must be monotonic and 2-D plaid (such as the data produced
by meshgrid). startx and starty define the starting positions of the streamlines.
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
fprintf(fileID, format, A, ...)
Fclose(fid1)
Related matlab code is : isentropic_fid.m
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.
The variables within the body of the function are all local variables.
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) e.g. integral(@(x) sin(x),0,pi)

q = integral2(fun handle,xmin,xmax,ymin,ymax) sum1=integral2(@(x,y) 0.3*x.*y,0,2.5,0,2);

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.
Related matlab code is streamfun2.m
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);
K2=F* dt; Related code: RK4tutorial.m
Y1=Y0+0.5K2; F=f(Y1); and BLASIUS.m
K3=F*dt;
Y1=Y0+K3; F=f(Y1)
K4=F*dt;
y
Y1=Y0+(K1+2K2+2K3+K4)/6; % Y1 is value of y at t=t+dt
Y0=Y1;
U
write R  K 4 code for the following ODEs U
dy u
1.  5 y when t  0, y  5, upto t  5
dt  ( y)
2. 2 f ( )  f ( ) f ( )  0 with BC as x
at   0 : f ( )  0, f ( )  0 and at   , f ( )  1
(Originaly , at y  0 : u  0, v  0 and at y  , u  U  )
Finite Difference Method

u ui1, j  ui, j u ui, j1  ui, j


Forward Difference, = and =
x x y y
u ui , j  ui1, j u ui, j  ui , j 1
Backward Difference, = and =
x x y y
u ui1, j  ui1, j u ui1, j  ui 1, j
Central Difference, = and =
x 2x y 2y
2u ui2, j  2ui1, j  ui, j
Forward Difference, =
x2 x2
2u ui, j2  2ui, j1  ui, j
and =
y2 y 2

Backward Difference,
2u ui, j  2ui1, j  ui2, j
=
x2 x2
 2u u  2u  u
i, j i , j 1 i , j 2
and =
y2 y 2

2u u
 i1, j  2ui, j  ui1, j
Central Difference, =
x2 x2
2u u
 i, j1  2ui, j  ui, j 1
and =
y2 y2
Matlab code: scr19.m
Matlab code: scr20.m
Matlab code: scr18.m
B T i n 1,1j  D T n 1
i, j  A T n 1
i1, j  C i
n

n1 n 
 T1, j   0 
  
1 0 0 0 . . . . 0 0   
   T2, j   C2, j  
0 D A 0 . . . . 0 0     
0  T3, j   C3, j 
B D A 0 . . . 0 0   
    
0 0 B D A 0 . . . .  T4, j   C4, j  
0  
0 0 B D A 0 . . .   . 

 . 
 

 . 
  c ( k  1)b( k )
. . 0 0 B . A 0 . .  .   c '( k )  c( k ) 
 
    d '( k  1)
. . 0 0 0 . . A 0 0  .  
 .  
0 . 0 0 0 0 . . A 0  
T
 N1, j 
C   a (k  1)b(k )
   N1, j   d '( k )  d ( k ) 
0 . 0 0 0 . 0 B D A T  C   d '( k  1)
N, j   N, j 
0
 0 0 0 0 . . 0 0 1 (N1)X (N1)  
TN1, j   1  
  (N1,1) N1,1

1 0 0 0 . . . . 0 0  n1 0
n
  T1 
0 d22 a23 0 . . . . . 0     
 T2   C2 
0 0 d' a 0 
 33 34 0 . . . .
  T3  C' 
'    3
0 0 0 d44 a45 0 . . . .  C' 
 T4 
 
 T5   4 Back substitution:
0 . 0 0 . . 0 . . . 
. .    . 
. 0 0 . . 0 . .   .   .  T (i ) 
c (i )  a (i ).T (i  1)
    d (i , i )
. . . . 0 0 . . 0 .   . 
   . 

0 . . . . 0 0 . aN1,N .  TN1  
T   . 
 '  CK 
0 . . . . . 0 0 dNN aN,N1  N 
 
TN1
0 0
 0 . . . . . 0 1 N1XN1 N1X1  1 
Matlab code: scr17.m

You might also like