Programming in Matlab
Programming in Matlab
By
Dr. S. C. RANA
y 25 x2
In Matlab: code is circle.m
x1=0: 0.01: 5;
y1=sqrt(25 - x1.^2);
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:
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)
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
-- Dashed line
: Dotted line
-. Dash-dot line
Marker type with Specifiers
P Pentagon
h Hexagon
Color Specifiers
Specifier Colour
r Red
g Green
B Blue
C Cyan
M Magenta
Y Yellow
K Black
w white
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 = integral3(fun handle,xmin,xmax,ymin,ymax,zmin,zmax)
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
Backward Difference,
2u ui, j 2ui1, j ui2, j
=
x2 x2
2u u 2u u
i, j i , j 1 i , j 2
and =
y2 y 2
2u u
i1, j 2ui, j ui1, j
Central Difference, =
x2 x2
2u u
i, j1 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
i1, j C i
n
n1 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
N1, j
C a (k 1)b(k )
N1, 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 (N1)X (N1)
TN1, j 1
(N1,1) N1,1
1 0 0 0 . . . . 0 0 n1 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 . aN1,N . TN1
T .
' CK
0 . . . . . 0 0 dNN aN,N1 N
TN1
0 0
0 . . . . . 0 1 N1XN1 N1X1 1
Matlab code: scr17.m