MATLAB Programming - Lecture Notes
MATLAB Programming - Lecture Notes
MATLAB PROGRAMMING
I M.Sc.,(Mathematics)
Code: MMAF181P50
Lecture Notes
Dr.K.Srinivasa Rao
Professor & Head
Department of Mathematics
Sri Chandra Sekharendra Saraswathi Viswa Mahavidyalaya
Enathur, Kanchipuram, Tamilnadu
Command history provides all the details of the functions typed and codes executed from
the command prompt in the recent past.
Workspace includes the names of variables generated during the running of certain
functions or codes. It also includes details regarding the size and types of variables
generated.
The current directory shows the location where the program is held or the directory from
where the current execution is running. Work folder in the drive where MATLAB is
installed is the default folder where programs are stored.
Help browser is the way to go through the details of the documentation made available
with MATLAB.
The prompt >> is the program prompt indicating that you are in the MATLAB
environment. Each instruction line in the command window begins with a prompt (>>),
which is automatically inserted by MATLAB. An instruction is executed after pressing the
enter key. The result of a command appears on the next line. The result can be
A MATLAB output
A MATLAB prompt, meaning that the instruction was executed and MATLAB is
waiting for the next command
An error message
The following examples indicates the input-output relations of MATLAB and its response
A MATLAB output
A=
output by MATLAB
54
A MATLAB prompt, meaning that the instruction was executed and MATLAB is waiting for
the next command
>> A=6*9; input by user
>> waiting for the next command (meaning that command is executed)
An error message
>> sin5
??? Undefined function or variable 'sin5'.
This activity of entering and executing commands is carried out in the main window (called
command window) and is used to enter single line commands only. Besides the main
window, there are two more windows are interest that are defined as follows:
The figure window, which is used to display graphs and plots executed by a program
entered at the command window
The editor or debugger window is the place where program are created and
modified. These programs can be saved in the form of files
When the user first enters MATLAB, the main program window or command window is
active. The edit window is used only when a program is created or modified and then
stored in a file. The graphic or figure window is created when plots are generated as a
result of executing a set of instructions.
Version of a MATLAB: In this workshop we are using R2007b (7.5.0) version but the latest
version available is R2019b (Version 9.7) - Released on 11th September, 2019. To know the
version of MATLAB, enter the following command in the command window.
>> version
ans =
7.5.0.342 (R2007b)
The command ver gives complete details of the version as shown in below
>> ver
MATLAB Operations:
Symbol Operation Example Answer
+ Addition Z= 6+3 Z=9
- Subtraction Z=6-3 Z=3
/ Right division Z=6/3 Z=2
\ Left division Z=3\6 Z=2
* Multiplication Z=6*3 Z=18
^ Exponentiation Z=6^3 Z=216
Use format long to get fixed point notation with 15 significant digits, e.g. try 100/7 and pi.
If you’re not sure of the order of magnitude of your output you can try format short g or
format long g. The g stands for ‘general’. MATLAB decides in each case whether to use fixed
or floating point. Use format bank for financial calculations; you get fixed point with two
decimal digits (for the cents). Try it on 10000/7.
Use format hex to get hexadecimal display.
Use format rat to display a number as a rational approximation (ratio of two integers), e.g.
pi is displayed as 355/113, a pleasant change from the tired old 22/7. Please note that even
this is an approximation! Try out format rat on √2 ande (exp(1)). The symbols + , - and a
space are displayed for positive, negative and zero elements of a vector or matrix after the
command format +. In certain applications this is a convenient way of displaying matrices.
The command format by itself reverts to the default format. You can always try help format
if you are confused!
Worksheet-I
Calculate the following values using Matlab
25
1. 3 9
8
2. 42 7 3. 2 1
6
4.
log125
10 5.
log10
e
6. cos( / 4) 7. sin ( / 3) 8. e
2 5 log ee
9.
The basic element in MATLAB is the matrix. The name MATLAB stands for Matrix
Laboratory, and the language syntax and commands are based on matrix (arrays)
operations and their extensions. Matrices and arrays are the fundamental representation of
information and data in MATLAB. You can create common arrays and grids, combine
existing arrays, manipulate an array's shape and content, and use indexing to access array
elements.
Arrays:
>>X=[1 -2 3 8 2 9] %Displays row vector or row matrix
X=
1 -2 3 8 2 9
>> Y=[0 5 9 7 -6 2];
>> X.*Y % Performs point wise multiplication
ans =
0 -10 27 56 -12 18
>> X.^2
ans =
1 4 9 64 4 81
>> X=[1 -2 9 8 2 9]
X=
1 -2 9 8 2 9
>> sqrt(X) % Displays square root of each element of X
>> 1./X % Displays reciprocal of X
>> 2.^X
ans =
2.0000 0.2500 512.0000 256.0000 4.0000 512.0000
>> max(X) %Displays maximum element in the vector
ans =
9
Sub.Code: MMAF181P50 Page 10
IM.Sc., _MATLAB Programming-Lecture Notes
2.2091e+013
>> mean(a)
ans =
5.5000
>> var(a)
ans =
7.8532
>> std(a)
ans =
2.8024
>> median(a)
ans =
5.5000
>> mode(a)
ans =
1
>> a(10) % Display the 10th element of a
ans =
5.2632
>> a(end) % Displays last element of a
>> a(10)=0; % Replaces 10th element by 0
>> a(1:3) % First three elements will be displayed
>> a(1:2:end) % Odd indexed elements will be displayed
Worksheet-II
Write a MATLAB program to find a factorial of n. (For example, write a program to find n!
for given n=15).
Write a MATLAB program that returns a sequence of first 50 even numbers and find sum
Write a MATLAB program that returns a sequence, consists of sequence of square of first 50
even numbers and find sum
Write a MATLAB program to find , for a=0.5; N=11 and N=21
Write a MATLAB program that adds all elements of X with even indexes (Here x is vector
containing particular number of elements).
Matrices:
>> A=[1 1 3;1 5 1;3 1 1]
A=
1 1 3
1 5 1
3 1 1
>> m= size(A) % Assigns dimension to m
m=
3 3
>> det(A) % Calculates the determinant of A
ans =
-36
>>rank(A) % Calculates the rank of A
ans =
3
>> diag(A) %Displays the principal diagonal elements of A
ans =
1
5
1
>> trace(A) % Displays the sum of the principal diagonal elements of A
ans =
7
>> A' % Displays the transpose of A
ans =
1 1 3
1 5 1
3 1 1
>> B=A^2
B=
11 9 7
9 27 9
7 9 11
>> A^-1 %Displays the inverse of A
ans =
-0.1111 -0.0556 0.3889
-0.0556 0.2222 -0.0556
0.3889 -0.0556 -0.1111
>> C=A+B
C=
12 10 10
10 32 10
10 10 12
>> D=A*B
D=
41 63 49
63 153 63
49 63 41
>> E=A.*B % Element wise multiplication of A and B
E=
11 9 21
9 135 9
21 9 11
>> A+2
ans =
3 3 5
3 7 3
5 3 3
>> 3*A
ans =
3 3 9
3 15 3
9 3 3
>> A/4
ans =
0.2500 0.2500 0.7500
0.2500 1.2500 0.2500
0.7500 0.2500 0.2500
>> 1./A
ans =
1.0000 1.0000 0.3333
1.0000 0.2000 1.0000
0.3333 1.0000 1.0000
>> A./B % Element wise division
ans =
0.0909 0.1111 0.4286
0.1111 0.1852 0.1111
0.4286 0.1111 0.0909
-2.0000
3.0000
6.0000
>> [V D]=eig(A) % Displays the Eigen vectors as columns of V, Eigen
values
are diagonal elements of D
V=
-0.7071 0.5774 0.4082
-0.0000 -0.5774 0.8165
0.7071 0.5774 0.4082
D=
-2.0000 0 0
0 3.0000 0
0 0 6.0000
Linear Indexing:
With MATLAB, you can refer to the elements of a matrix with a single subscript, A(k).
MATLAB stores matrices and arrays not in the shape that they appear when displayed in
the MATLAB Command Window, but as a single column of elements. This single column is
composed of all of the columns from the matrix, each appended to the last. So, matrix A
>>A = [2 6 9; 4 2 8; 3 5 1]
A=
2 6 9
4 2 8
3 5 1
is actually stored in memory as the sequence 2, 4, 3, 6, 2, 5, 9, 8, 1.
The element at row 3, column 2 of matrix A (value = 5) can also be identified as element 6
in the actual storage sequence. To access this element, you have a choice of using the
standard A(3,2) syntax, or you can use A(6), which is referred to as linear indexing.
Sub.Code: MMAF181P50 Page 17
IM.Sc., _MATLAB Programming-Lecture Notes
>> A(6)
Ans=
5
>> A(3,2) % Displays second row, second column element of A
ans =
5
>> A(:,2) % Displays second column of A
ans =
6
2
5
>> A(1,:) % Displays first row of A
ans =
2 6 9
>> A(2,3)=-6 % Replaces A(2,3) element by -6
A=
2 6 9
4 2 -6
3 5 1
>> A([1 6 8])=[-1 -2 -3]
A=
-1 6 9
4 2 -3
3 -2 1
>> A(3,:)=[1 0 1] % Replaces 3rd row of A by [1 0 1]
A=
2 6 9
4 2 -6
1 0 1
Sub.Code: MMAF181P50 Page 18
IM.Sc., _MATLAB Programming-Lecture Notes
Special Matrices
>> ones(5)
ans =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
>> ones(2,3)
ans =
1 1 1
1 1 1
>> zeros(3,2)
ans =
0 0
0 0
0 0
The command eye(N) displays the N-by-N identity matrix and eye(M,N) or eye([M,N])
displays an M-by-N matrix with 1's on the diagonal and zeros elsewhere. For example the
command eye(3) displays the following output.
1 0 0
0 1 0
0 0 1
>> eye(4,3)
ans =
1 0 0
0 1 0
0 0 1
0 0 0
>> eye(3,4)
ans =
1 0 0 0
0 1 0 0
0 0 1 0
R = rand(N) returns an N-by-N matrix containing random values drawn from the interval
[0,1]. For example the command A=rand(5) gives the following output
A=
0.8147 0.0975 0.1576 0.1419 0.6557
0.9058 0.2785 0.9706 0.4218 0.0357
0.1270 0.5469 0.9572 0.9157 0.8491
0.9134 0.9575 0.4854 0.7922 0.9340
0.6324 0.9649 0.8003 0.9595 0.6787
>> A=rand(2,4)
A=
0.7577 0.3922 0.1712 0.0318
0.7431 0.6555 0.7060 0.2769
repmat replicate and tile an array. B = repmat(A,M,N) creates a large matrix B consisting
of an M-by-N tiling of copies of A. The size of B is [size(A,1)*M, size(A,2)*N]. The statement
repmat(A,N) creates an N-by-N tiling. For example the command repmat(eye(3),2,3) gives
the following output
1 0 0 1 0 0 1 0 0
0 1 0 0 1 0 0 1 0
0 0 1 0 0 1 0 0 1
1 0 0 1 0 0 1 0 0
0 1 0 0 1 0 0 1 0
0 0 1 0 0 1 0 0 1
In the command repmat(A,r,c) , A can be scalar, vector, or matrix; r is the number of times
the rows of A will be replicated; c is the number of times the columns of A will be
replicated.
0 0 0 1
1 1 0 0
1 0 1 1
0 0 0 0
>>ind=find(p<25))
ind =
2
3
6
11
13
15
>>p(p<25)=10
p=
39 96 45 10
10 10 74 78
10 35 10 10
94 82 69 93
Swapping Rows and Columns: We can swap the elements in array. For example,
>> s=[8 9 4 15 4 7 10];
>> r=s([2 1 3 4 5 6 7])
r=
9 8 4 15 4 7 10
>> p(:,[2 1 3 4])
ans =
96 39 45 10
10 10 74 78
35 10 10 10
82 94 69 93
Worksheet-III
1. Write a MATLAB program that returns 6x6 random matrix C with random elements
consists of integers between 1 and 100
2. Determine the main diagonal of C
3. The sum and product of the elements of the main diagonal of C
4. The average of the elements of the main diagonal of C
5. The maximum and minimum values of the elements and corresponding indices on
the main diagonal of C
6. Find rank and determinant of C
7. Inverse and transpose of C
8. Square each element of C
9. Display the second row of C
The above system can be written in matrix form as AX=B, where and
B=
X=
1.0000
1.0000
1.0000
Another method to solve system is based on Gauss Jordan elimination with partial pivoting.
The command rref([A B]), produces the reduced row echelon form of A.
X=rref([A B])
X=
1 0 0 1
0 1 0 1
0 0 1 1
LU Decomposition
A square matrix A can be factorized into lower(L) and upper(U) triangular matrices, when
possible, by using the following command, where L*U=A
>> [L U]=lu(A)
L=
0.3333 0.1429 1.0000
0.3333 1.0000 0
1.0000 0 0
U=
3.0000 1.0000 1.0000
0 4.6667 0.6667
0 0 2.5714
>> L*U
1.0000 1.0000 3.0000
1.0000 5.0000 1.0000
3.0000 1.0000 1.0000
Programming using trigonometric functions:
Anonymous Functions:
An anonymous function is a function of one or more variables that you create on the
command line for subsequent evaluations. Such a function especially useful if you need to
evaluate the function several times (with different output, especially in MATLAB
programming) during a single MATALB session and you do not care to code it in a function
file and save later use.
The syntax is
fn_name=@( variables) function expression
>> f=@(x) x*cos(x)-x*log(x+10)+100
f =
@(x)x*cos(x)-x*log(x+10)+100
>> f(1)
ans =
98.1424
Worksheet-IV
The following exercises are meant to be answered by a single MATLAB command. The
command may be involved (i.e., it may use a number of parentheses or calls to functions)
but can, in essence, be solved by the execution of a single command. If the command is too
complicated, feel free to break it up over two or more lines.
Create a vector of the even numbers between 31 and 75.
Let x = [2 5 1 6].
a. Add 16 to each element
b. Add 3 to just the odd-index elements
c. Compute the square root of each element
d. Compute the square of each element
Let x = [3 2 6 8]' and y = [4 1 3 5]' (NB. x and y should be column vectors).
a. Add the sum of the elements in x to y
b. Raise each element of x to the power specified by the corresponding element in y.
c. Divide each element of y by the corresponding element in x
d. Multiply each element in x by the corresponding element in y, calling the result "z".
e. Add up the elements in z and assign the result to a variable called "w".
f. Compute x'*y - w and interpret the result
Create a vector x with the elements (don’t manually assign values; use MATLAB
commands).
a. 2, 4, 6, 8
b. 10, 8, 6, 4, 2, 0, -2, -4
c. 1, 1/2, 1/3, 1/4, 1/5
d. 0, 1/2, 2/3, 3/4, 4/5
Create a vector x with the elements,
xn = (-1)n+1/(2n-1)
Add up the elements of the version of this vector that has 100 elements.
Given a vector, t, of length n, write down the MATLAB expressions that will correctly
compute the following:
a. ln(2 + t + t2)
b. et(1 + cos(3t))
c. cos2(t) + sin2(t)
d. tan-1(1) (this is the inverse tangent function)
e. cot(t)
f. sec2(t) + cot(t) - 1
Test that your solution works for t = 1:0.2:2
Worksheet-V
The following exercises are meant to be answered by a single MATLAB command. The
command may be involved (i.e., it may use a number of parentheses or calls to functions)
but can, in essence, be solved by the execution of a single command. If the command is too
complicated, feel free to break it up over two or more lines.
1. Given x = [3 1 5 7 9 2 6], explain what the following commands "mean" by by
summarizing the net result of the command.
a. x(3) b. x(1:7) c. x(1:end) d. x(1:end-1)
e. x(6:-2:1) f. x([1 6 2 1 1]) g. sum(x)
2. Given the array A = [ 2 4 1 ; 6 7 2 ; 3 5 9], provide the commands needed to
a. assign the first row of A to a vector called x1
b. assign the last 2 rows of A to an array called y
c. compute the sum over the columns of A
d. compute the sum over the rows of A
e. compute the standard error of the mean of each column of A (NB. the standard error of
the mean is defined as the standard deviation divided by the square root of the number of
elements used to compute the mean.)
3. Given the arrays x = [1 4 8], y = [2 1 5] and A = [3 1 6 ; 5 2 7],
Determine which of the following statements will correctly execute and provide the result.
If the command will not correctly execute, state why it will not. Using the command whos
may be helpful here. a. x + y b. x + A c. x' + y d. A -
[x' y']
e. [x ; y'] f. [x ; y] g. A - 3
4. Given the array A = [2 7 9 7 ; 3 1 5 6 ; 8 1 2 5], explain the results of the following
commands:
a. A' b. A(:,[1 4]) c. A([2 3],[3 1])
d. reshape(A,2,6) e. A(:) f. flipud(A)
g. fliplr(A) h. [A A(end,:)] i. A(1:3,:)
j. [A ; A(1:2,:)] k. sum(A) l. sum(A')
m. sum(A,2) n. [ [ A ; sum(A) ] [ sum(A,2) ; sum(A(:)) ] ]
5. Given the array A from problem 4, above, provide the command that will
a. assign the even-numbered columns of A to an array called B
b. assign the odd-numbered rows to an array called C
c. convert A into a 4-by-3 array
d. compute the reciprocal of each element of A
e. compute the square-root of each element of A
Worksheet-VI
1. Create a two random matrices M, N of order 6X6, whose elements consists from 1 to 100.
2. Using command delete the second row of the matrix M and name it as P
3. Using command delete the 6th column of the matrix N and name it as Q
4. Add the second column of M and to the first column of N
5. Convert the matrix M to column and row vectors
6. Using command create the matrix R consisting of maximum values of either M or N
7. Using command create the matrix S consisting of minimum values of either M or N
8. Using command create a matrix T by replacing all the elements above the main diagonal
of M by zeros
9. Using command create a matrix U by replacing all the elements below the main diagonal
of N by zeros
10. Perform the command cumprod(M), observe the output
11. Perform the command sort(M), observe the output
12. Perform the command sqrt(M), observe the output
13. Perform the command sqrtm(M), observe the output
14. Create the function f ( x) x2 cos x 2 / x and (a) evaluate f(0), f(1), f(pi/2) (b)
Evaluate f(x) where x=[0 1 pi/2 pi]
15. Create the following functions:
f(x) = x4-8x3+17x2-4x-20
g(x) = x2-4x+4
h(x) = x2-4x-5
(a) Evaluate f(x)-g(x)h(x) at x=3
(b) Evaluate f(x)-g(x)h(x) at x=[1 2 3 4 5]
(c ) Evaluate f(x)/g(x) –h(x) for any x
3. PLOTTING
MATLAB not only helps us for calculation but also helps us in data analysis and
visualization by plotting graphs and waveforms. It provides a variety of functions for
displaying data as 2-D or 3-D graphics. The commands to produce simple plots are
surprisingly simple. For complicated graphs and special effects there are a lot of built-in
functions that enable the user to manipulate the graphics window in many ways.
For 2-D graphics, the basic command is:
plot(xdata, ydata)
This command produces plot with xdata on the horizontal axis and ydata on the vertical
axis. To produce overlay plots you can specify any number of pairs of vectors as the
argument of the plot command.
Plot the curve y sinx over the range 0 x 2
>> x=linspace(0,2*pi,100); 1
Sinx versus x
0.6
0.2
>> grid on
Y-axis
-0.2
>> xlabel('X-axis')
-0.4
-0.8
If you execute the command stem(x,y) instead of plot(x,y), we get the following output
sinx versus x
1
0.8
0.6
0.4
0.2
Y-Axis
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6
X-axis
Figure-1
If we execute the command fill(x,y,’g’) command, we get the following output (% ‘g’
represents green colour)
Sinx versus x
1
0.8
0.6
0.4
0.2
Y-axis
0
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6
X-axis
sin x
Plot the curve y in the interval [-50,50]
x
>> x=linspace(-50,50,1000); 1
Sinx/x curve versus x
0.4
>> grid on Y-Axis
0.2
>> xlabel('X-Axis') 0
0.6
>> area(x,y)
0.4
>> x1=x(46:55);y1=y(46:55); 0
>> area(x1,y1,'facecolor','y')
-0.2
-0.4
-8 -6 -4 -2 0 2 4 6 8
0.3
>> plot(x,y)
0.2
>> grid on
Y-Axis
0.1
>> xlabel('X-Axis') 0
-0.1
versus x')
X-Axis
Overlay Plotting:
Plot the curves y sin x, y 2sin x, y 3sin x over the range 0 x 2
>> x=linspace(0,2*pi,100); 3
Sinx,2Sinx,3Sinx versus x
Sinx
>> y1=sin(x); 2Sinx
2 3Sinx
>> y2=2*sin(x);
1
>> y3=3*sin(x);
Y-Axis
>> plot(x,y1,x,y2,x,y3) 0
>> grid on -1
>> xlabel('X-Axis') -2
>> ylabel('Y-Axis')
-3
0 1 2 3 4 5 6
>> title('Sinx,2Sinx,3Sinx X-Axis
versus x')
>> x=linspace(-3,3,100); 9
y=x 2,x+2y-3=0 over[-3,3]
y=x 2
8
>> y1=x.^2;y2=1/2*(3-x);
x+2y-3=0
>> plot(x,y1,x,y2) 6
Y-axis
4
0
-3 -2 -1 0 1 2 3
X-axis
Plot y x x 3 for = [-5 0 5 45] over a range of [-5 5] using function of two variables
,x
>> f = @(mu,x) mu*x-x.^3;
>> x = linspace(-5,5);
>> y= [f(-5,x) f(0,x) f(5,x) f(45,x)];
>> plot(x,f(-5,x),x,f(0,x),x,f(5,x),x,f(45,x))
>> grid 150
>> ylabel('f(\mu,x)=\mu x- 50
x^3')
f(,x)= x-x 3
-50
-100
-150
-5 -4 -3 -2 -1 0 1 2 3 4 5
x
A cycloid is the curve traced by a point on the rim of a circular wheel as the wheel rolls
along a straight line without slipping. Equations in parametric form:
x a( sin )
y a(1 cos )
This is a curve described by a point P on a circle of radius a rolling on x-axis
Epicycloids:
In geometry, a epicycloids is a special plane curve generated by the trace of a fixed point on
the circumference of a small circle that rolls without slipping around a larger circle. It is
comparable to the cycloid but instead of the circle rolling along a line, it rolls on a circle.
If the smaller circle has radius r, and the larger circle has radius R = kr, then the parametric
equations for the curve can be given by either:
Rr
x(t ) ( R r ) cos t r cos t
r
Rr
y (t ) ( R r ) sin t r sin t
r
or
3 5
4
2
3
1 2
1
0
0
-1 -1
-2
-2
-3
-3 -4
-3 -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5
-5
-5 -4 -3 -2 -1 0 1 2 3 4 5
Hypocycloid
In geometry, a hypocycloid is a special plane curve generated by the trace of a fixed point
on a small circle that rolls within a larger circle. It is comparable to the cycloid but instead
of the circle rolling along a line, it rolls within a circle.
If the smaller circle has radius r, and the larger circle has radius R = kr, then the parametric
equations for the curve can be given by either:
Rr
x(t ) ( R r ) cos t r cos t
r x(t ) r (k 1) cos t r cos (k 1)t
or
Rr y (t ) r (k 1)sin t r sin (k 1)t
y (t ) ( R r ) sin t r sin t
r
If k is an integer, then the curve is closed, and has k cusps.
If k is a rational number, say k = p/q expressed in simplest terms, then the curve
has p cusps.
If k is an irrational number, then the curve never closes.
For example, if k=4, then we get the curve has four cusps(asteroid).
>>k=4; 4
>>t=0:0.01:2*pi; 3
>>x=(k-1)*cos(t)+cos((k-1)*t); 2
>>y=(k-1)*sin(t)-sin((k-1)*t); 1
>>fill(x,y,'y')
0
-1
-2
-3
-4
-4 -3 -2 -1 0 1 2 3 4
>>k=2.1; 2.5
>>t=0:0.01:2*pi; 2
>>x=(k-1)*cos(t)+cos((k- 1.5
1)*t); 0.5
>>y=(k-1)*sin(t)-sin((k- 0
1)*t); -0.5
-1
>>fill(x,y,'y') -1.5
-2
-2.5
-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5
y=x 2 y=x 3
4 10
3 5
2 0
1 -5
0 -10
-2 -1 0 1 2 -2 -1 0 1 2
y=1/x y=exp(x)
100 8
50 6
0 4
-50 2
-100 0
-2 -1 0 1 2 -2 -1 0 1 2
To create a subplot with one large plot axis on the left side and two small plot axes in a
column on the right, the following may be used.
>> subplot(2,2,2), ezplot('sin(x)')
>> subplot(2,2,4), ezplot('cos(x)')
>> subplot(2,2,[1 3]), ezplot('sin(x)^2./x.^2')
The resulting figure is as below
The ezplot() is an easy to use function plotter. The syntax ezplot(fun) plots the function
over the default domain -2*pi<2*pi.
Polar Plotting:
In mathematics, the polar coordinate system is a two dimensional coordinate system in
which each point on a plane is determined by a distance from a reference point and
an angle from a reference direction. The command [theta, rho] = cart2pol(x,y) transforms
corresponding elements of the two-dimensional Cartesian coordinate arrays x and y into
polar coordinates theta and rho. The command [theta,rho,z] = cart2pol(x,y,z) transforms
three-dimensional Cartesian coordinate arrays x, y, and z into cylindrical
coordinates theta, rho, and z. Similarly the command [x, y] =
pol2cart(theta,rho) transforms corresponding elements of the polar coordinate
arrays theta and rho to two-dimensional Cartesian coordinates and the command [x,y,z] =
pol2cart(theta,rho,z) transforms corresponding elements of the cylindrical coordinate
arrays theta, rho, and z to three-dimensional Cartesian, or xyz, coordinates.
The syntax polar(theta, rho) makes a plot using polar co-ordinates of the angle theta,
versus the radians rho. For example
>> t=linspace(0,2*pi,100);
>> r=2*cos(t); 120
90 2
60
>> polar(t,r) 1.5
>> r2=-r;
>> polar(t,r2) 210 330
>> hold on
>> r3=-r1; 240 300
210 330
210 330
240 300
270 240 300
270
90 90
1 1
120 60 120 60
0.8 0.8
0.6 0.6
150 30 150 30
0.4 0.4
0.2 0.2
180 0 180 0
3 90
10
150 30
2 120 60
8
1
6
150 30
180 0 4
180 0
210 330
240 300
270
90 2 90 2
120 60 120 60
1.5 1.5
150 1 30 1
150 30
0.5
0.5
180 0
180 0
210 330
210 330
240 300
270 240 300
270
3-D Plotting
A function named plot3() can be used to generate 3-D plots in MATLAB. If the function is
used as plot3(x,y,z), the vectors are plotted against the rows or columns of the matrix,
depending whether the vectors ‘ lengths equal the number of rows or the number of
columns. If the lengths are different an error will be created.
>> t=0:pi/70:15*pi;
>> x=cos(2*t); y=sin(2*t); 50
40
>> plot3(x,y,t) 30
20
>> grid on 10
0
1
0.5 1
0 0.5
0
-0.5 -0.5
-1 -1
>> scatter3(x,y,t)
40
30
20
>> grid on 10
0
1
0.5 1
0.5
0
0
-0.5
-0.5
-1 -1
Example:
>>t = 0:pi/500:40*pi; 4
>>x = (3 + cos(sqrt(32)*t)).*cos(t); 3
>>z = (3 + cos(sqrt(32)*t)).*sin(t); 1
>>plot3(x,y,z) 0
-1
-2
-3
-4
1
0 2 3 4
-4
-1 -3 -2 -1 0 1
Surface Plot:
At times a programmer has to deal with ordered pairs, i.e., data that is dependent on both x
and y values as z=f(x,y). This can be done by computing a z value for each x,y pair which in
effect is to iterate through a nested loop, but one of the major advantages of MATLAB is
that it can deal with matrices without resorting to looping. If the data available is in a
matrix format this can be done easily. If data is assigned to x and y considered to be vectors,
MATLAB provides a useful function called meshgrid that can be used to simplify the
generation of X and Y matrix arrays used in 3-D plots. It is invoked using the form
[X,Y]=meshgrid(x,y), where x and y are vectors that help specify the region in which co-
ordinates, defined by element pairs of the matrices X and Y, will lie. The matrix X will
contain replicated rows of the vector X, while Y will contain replicated columns of vector y.
One of the basic surface plotting is mesh. The syntax is mesh(X,Y,Z). mesh(X,Y,Z) draws a
wireframe mesh with color determined by Z so color is proportional to surface height. If X
and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). In this case,
(X(j), Y(i), Z(i,j)) are the intersections of the wireframe grid lines; X and Y correspond to
the columns and rows of Z, respectively. If X and Y are matrices, (X(i,j), Y(i,j), Z(i,j)) are the
intersections of the wireframe grid lines.
Consider the following plot. It creates many criss-crossed lines that look like a net spread
over the surface defined by the data points.
>>[X,Y] = meshgrid(-3:.125:3); 8
>>Z = peaks(X,Y);
>>mesh(X,Y,Z) 10 6
>>colorbar 5
0
0
-5
-2
-10 -4
2 2
0 0 -6
-2 -2
>>[x y]=meshgrid(-3:0.1:3);
>>z= x.^2+y.^2; 20
15
>>surf(x,y,z)
10
0
4
2 4
0 2
0
-2 -2
-4 -4
>>z= x.^2-y.^2; 10 6
>>surf(x,y,z) 5
2
0
0
>> colorbar -5 -2
Note: Colorbar acts as a legend
for colors -10
4
-4
2 4 -6
0 2
0 -8
-2 -2
-4 -4
We can add different maps, for example colormap winter, colormap spring , colormap jet
etc., (Try), also we can fix the levels (m) of colors with the commands colormap spring(m),
colarmap jet(m) etc., (Try)
x2 y 2
4
Plot z cos x.cos y.e
; -5<x, y<5
>> [x y]=meshgrid(-5:0.1:5);
>> z=cos(x).*cos(y).*…
exp(-sqrt(x.^2+y.^2)/4);
>> surf(x,y,z)
>> axis(‘off’)
5
Plot z ; -3<x,y<3
1 x2 y 2
0
>> x=linspace(-3,3,50); -1
>> y=x; -2
-3
>> [x y]=meshgrid(x,y); -4
>> z=-5./(1+x.^2+y.^2); -5
60
50
>> waterfall(z) 40
30
40
20 20
10
>> hidden off 0 0
x2 y 2
4
Plot z cos x.cos y.e
; -5<x, y< 1
exp(-sqrt(x.^2+y.^2)/4);
-0.5 5
>> surf(x,y, 5
0 0
-5 -5
Worksheet-VII
f ( x)
1. Plot f(x) and over x [5 5] where f(x), g(x) and h(x) are in problem number
g ( x ) h( x )
15, worksheet VI.
x2 x2
2. Plot y=cosx and z 1 for 0 x
2 24
x3 x5
3. Plot y= sinx; y=x and z x in 0 x
6 150
4. Plot z sin 2 x sin 2 y in –pi/2<x,y<pi/2
xy ( x 2 y 2 )
5. Plot z in -3<x,y<3
x2 y 2
6. Plot z= sinx+cosy in 0<x,y <10
x2 y 2
7. Plot the contour plot z cos x cos ye 4
in -5 < x, y<5 using the command surfc(z)
8. Plot the above with the command surfl(z) . (Use commands ‘shading interp’ and
colormap hot commands to get different colours).
Hint: The command ‘shading interp’ gets rid of black lines in the surface plot
4. MATLAB PROGRAMMING
MATLAB provides its own language, which incorporates many features from C. In some
regards, it is a higher-level language than most common programming languages, such as
Pascal, Fortran, and C, meaning that you will spend less time worrying about formalisms
and syntax. For the most part, MATLAB’s language feels somewhat natural.
Example 2: Write a MATLAB program that returns the sequence consisting of square of the
first 50 even numbers, and identify and display the first, fifth, and tenth element of the
sequence.
>> n=0:2:98;
>>sq_even=n^.2
>> sq_even(5) % To identify 5th element
Another way is just by clicking the New M-file icon from the toolbar of the command
window. Or, select File menu and from the dropdown menu select New and then select M-
file. When a new window is opened, we can type program codes in it.
Once we open a new file in editor window, we can save it at any time, just at the beginning
or at very end of writing the program code or in the middle of writing the program. Most
often we save it in the middle or after we finish typing the code. There are two save options
available: Save and Save as. Save as option allows us to save the program in any directory
and Save will save the file in the current working directory. In either case, the Save dialog
box will appear and we have to enter appropriate file name. This filename will be used as
command when running the program. Hence, a suitable name may be given to remind us of
about the purpose of the file.
Once a program file is saved, we can run it easily in different ways. We can directly run the
program from the editor window by clicking the save and run icon present in the toolbar. If
there is a error, the line number and accompanying error message will be displayed.
Modify if there is any syntax error, then save and run it. If there is no error, it should run
properly. Once a script file is tested OK, then its filename becomes command. We can run
the program by typing its filename in the command window.
Writing & Executing the Script File
Open a new editor and type the following lines as shown below. Save the file with suitable
name and run the program
clc
n=input(‘Enter the Value of n=’);
fact=prod(1:n);
fprintf(‘The factorial value of %d is %d\n’, n,fact)
If-end Statement
The syntax and format of the simplest form of the if-end statement is as follows
if
<condition>
<statements>
end
Only one decision-making <condition> is used, and if this <condition> is true, the
<statements> are executed, followed by the end(exit)
However, if the <condition> is false, then the <statements> are not executed, followed by
the end(exit).
The if-end statement can be expanded to include two different paths by executing two
different sets of statements based on a single decision-making condition.
if
<condition>
<statements-1>
else
<statements-2>
end
Meaning that if<condition> is true, then<statements-1> is executed followed by the
end(exit); but if <condition> is not true, then <statements-2> is executed followed by the
end(exit).
A multiple path can be set based on multiple decision-making conditions by using the
general form of the if-end statement. The syntax and format are as follows:
if
<condition-1>
<statements-1>
elseif
<condition-2>
<statements-2>
elseif
<condition-3>
<statements-3>
elseif
<condition-4>
<statements-4>
.
.
.
else
<statements-n>
end
Meaning the if<condition-1> is true, then the <statement-1> is executed followed by the
end(exit); but if <condition-1> is not true, then MATLAB checks if <condition-2> is true; if
it is true, then <statement-2> is executed followed by the end(exit), otherwise the
<condition-3> is tested, and so on; if none of the n-1 conditions are true, then MATLAB
executes <statement-n> followed by end(exit).
for-end Statement
The syntax of for-end statement as follows:
for <range>
<statements>
end
referred as the for-end statement is used to create a loop that executes repetitively the
<statements> a fixed number of times based on the specified <range>. The specified
<range> is frequently given by a vector or a matrix.
(A,B) 1 2 1 3
0 1 1 4
0 0 8 24 R R (7) R
3 3 2
a(3,:)=a(3,:)-k*a(1,:);
% With A(2,2) as pivot element
k=a(3,2)/a(2,2);
a(3,:)=a(3,:)-k*a(2,:);
a
%% Back Substituion
x=ones(3,1);
x(3)=a(3,end)/a(3,3);
x(2)=(a(2,end)-a(2,3)*x(3))/a(2,2);
x(1)=(a(1,end)-a(1,2)*x(2)-a(1,3)*x(3))/a(1,1);
Sol=x
MATLAB Code for Gauss Jordon Method
a(3,:)=a(3,:)/a(3,3);
%% Solution
Solution_X=a(:,end)
Exercise:- Solve the following problems by both Gauss –elimination & Gauss Jordan method
1) 2x+3y-z=5, 4x+4y-3z=3, and 2x-3y+2z=2 (Ans. x=1,y=2,z=3)
2) 5x+y+z+t=4, x+7y+z+t=12, x+y+6z+t=-5, x+y+z+4t=-6 (Ans x=1,y=2,z=-1, t=-2)
3) x+y+z+w=2, 2x-y+2z-w=-5, 3x+2y+3z+4w=7, x-2y-3z+2w=5. (Ans x=0,y=1, z=-1,
w=2)
Numerical Integration:
b
The process of finding a definite integral f ( x)dx
a
from a set of tabulated values ( xi , yi ) ;
i=0,1,..n, where yi =f(xi), xo=a and xn =b is called numerical integration. This process when
applied to a function of a single variable is called quadrature.
Let us divide the interval (a, b) into n sub- intervals of width h(=(b-a)/n) so that
x0 a, x1 a h,...xn x0 nh b
Trapezoidal Rule:
b
h
f ( x)dx 2 [( y
a
0 yn ) 2( y1 y2 ... yn 1 )]
6
dx
Problem: Evaluate 1 x
0
2
using Trapezoidal rule, dividing the interval into 6 equal parts.
Solution:
Here n=6; a=0; b=6. Therefore h=(b-a)/n=1.
x 0 1 2 3 4 5 6
y=f(x) 1 0.5 0.2 0.1 0.0588 0.0385 0.027
By Trapezoidal rule
6
dx h
1 x
0
2
= [( y0 y6 ) 2( y1 y2 y3 y4 y5 )]
2
=1.1408
6
dx
Problem: Evaluate 1 x
0
2
using Simpson’s 1/3 rule, dividing the interval into 6 equal parts.
Solution:
Here n=6; a=0; b=6. Therefore h=(b-a)/n=1.
x 0 1 2 3 4 5 6
y=f(x) 1 0.5 0.2 0.1 0.0588 0.0385 0.027
By Simpson’s 1/3 rule
6
dx h
1 x
0
2
= [( y0 y6 ) 4( y1 y3 y3 y5 ) 2( y2 y4 )]
3
=1.3662
MATLAB Code for Simpson’s 1/3rd Rule
f =@(x) 1./(1+x.^2);
a=0; b=6; n=6;
h=(b-a)/n;
xi=a:h:b;
fa = f(xi(1));
fb = f(xi(end));
feven = f(xi(3:2:end-2));
fodd = f(xi(2:2:end));
s=h/3*(fa+2*sum(feven)+4*sum(fodd)+fb)
f=@(x) (1./(1+x.^2));
a=0; b=1;n=6;
h=(b-a)/n;
x=a:h:b;
fa=f(x(1));
fb=f(x(end));
f_3m=f(x(4:3:end-3));
frem=f(x(2:end-1));
s=(3*h/8)*((fa+fb)+3*sum(frem)-sum(f_3m))
f=@(x) x-cos(x);
a=0;b=1; % f(a)<0 ; f(b)>0
for i=1:14
c=(a+b)/2;
f_value(i)=f(c);
if f(c)>0
b=c;
else
a=c;
end
end
root=c
er=f_value-f(c);
plot(er, ':.') % Error Plotting
Newton Raphson Method
Let x=x0 be an approximate root of the equation f(x)=0 and x=x1 be the exact root such
that x-x0 =h is small. The Newton –Rapshon formula to find a better approximation to x1 is
f ( x1 )
x2 x1
f ( x1 )
f ( xi )
Generally, xi 1 xi
f ( xi )
Problem:
f(0)=-2 <0
f(1)=1.4597>0
A root is lies between 0 and 1.
By Newtons- Raphson method,
x1=0.62002
x2=0.60712
x3=0.60710
x4= 0.60710
Hence the root is 0.60710.
MATLAB Code for Newton Rapshon Method:
f=@(x) 3*x-cos(x)-1;
dif=@(x) 3+sin(x);
y=0;
for i=1:10
a(i)=y;
f_value(i)=f(y);
x=y-(f(y)/dif(y));
y=x;
end
root=y
er=f_value-f(y)
plot(er,'.:')
Bibliography