Workshop Manual
Workshop Manual
1|Page
4.3 Loop Control Statements ....................................................................................... 22
CHAPTER - 5 MATLAB – Plotting .................................................................................... 24
5.1 Graph Plotting Commands ..................................................................................... 24
5.2 Adding Title, Labels, Grid Lines and Scaling on the Graph ..................................... 26
5.2.1 Example ......................................................................................................... 26
5.3 Drawing Multiple Functions on the Same Graph ................................................... 27
5.3.1 Example ......................................................................................................... 27
5.4 Setting Colors on Graph ......................................................................................... 28
5.4.1 Example ......................................................................................................... 28
5.5 Setting Axis Scales .................................................................................................. 29
5.5.1 Example ......................................................................................................... 29
5.6 Generating Sub-Plots ............................................................................................. 30
5.6.1 Example ......................................................................................................... 30
CHAPTER - 6 MATLAB – Graphics ................................................................................... 31
6.1 Drawing Bar Charts ................................................................................................ 31
6.1.1 Example ......................................................................................................... 31
6.2 Drawing Contours .................................................................................................. 32
6.2.1 Example ......................................................................................................... 32
6.3 Three Dimensional Plots ........................................................................................ 33
6.3.1 Example ......................................................................................................... 33
CHAPTER - 7 MATLAB – Functions ................................................................................. 35
7.1 Example .................................................................................................................. 35
7.2 Anonymous Functions ............................................................................................ 36
7.2.1 Example ......................................................................................................... 36
7.3 Primary and Sub-Functions .................................................................................... 36
7.3.1 Example ......................................................................................................... 37
7.4 Nested Functions ................................................................................................... 37
7.4.1 Example ......................................................................................................... 38
7.5 Private Functions.................................................................................................... 38
7.5.1 Example ......................................................................................................... 38
7.6 Global Variables ..................................................................................................... 39
7.6.1 Example ......................................................................................................... 39
2|Page
CHAPTER - 1 Basic Matlab Environment
1.1 MATLAB Desktop
The main working window in MATLAB is called the desktop. When you start MATLAB,
the desktop appears in its default layout:
3|Page
1.3 Command Window
This is the main area where you enter commands at the command line, indicated by
the command prompt (>>).
1.4 Workspace
The workspace shows all the variables you create and/or import from files.
4|Page
CHAPTER - 2
Matlab Basics Commands, Operators & Data Types
2.1 General Commands
Command Purpose
Clc Clears command window.
Clear Removes variables from memory.
global Declares variables to be global.
Help Searches for a help topic.
Quit Stops MATLAB.
Who Lists current variables.
Whos Lists current variables (long display).
The fscanf and fprintf commands behave like C scanf and printf functions.
They support the following format codes –
Format Code Purpose
%s Format as a string.
%d Format as an integer.
%f Format as a floating-point value.
%e Format as a floating-point value in scientific notation.
%g Format in the most compact form: %f or %e.
\n Insert a new line in the output string.
\t Insert a tab in the output string.
5|Page
Format Purpose
6|Page
For non-scalar A and B, the number of columns of A must be equal
to the number of rows of B. A scalar can multiply a matrix of any
size.
Array multiplication. A.*B is the element-by-element product of the
.* arrays A and B. A and B must have the same size, unless one of them
is a scalar.
Slash or matrix right division. B/A is roughly the same as B*inv(A).
/
More precisely, B/A = (A'\B')'.
Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A
./
and B must have the same size, unless one of them is a scalar.
Backslash or matrix left division. If A is a square matrix, A\B is
roughly the same as inv(A)*B, except it is computed in a different
way. If A is an n-by-n matrix and B is a column vector with n
\
components, or a matrix with several such columns, then X = A\B is
the solution to the equation AX = B. A warning message is displayed
if A is badly scaled or nearly singular.
Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A
.\
and B must have the same size, unless one of them is a scalar.
Matrix power. X^p is X to the power p, if p is a scalar. If p is an
integer, the power is computed by repeated squaring. If the integer
^ is negative, X is inverted first. For other values of p, the calculation
involves eigenvalues and eigenvectors, such that if [V,D] = eig(X),
then X^p = V*D.^p/V.
Array power. A.^B is the matrix with elements A(i,j) to the B(i,j)
.^ power. A and B must have the same size, unless one of them is a
scalar.
Matrix transpose. A' is the linear algebraic transpose of A. For
'
complex matrices, this is the complex conjugate transpose.
Array transpose. A.' is the array transpose of A. For complex
.'
matrices, this does not involve conjugation.
7|Page
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
8|Page
bitset(a, pos) Set bit at specific location pos of a
bitshift(a, k) Returns a shifted to the left by k bits, equivalent to
multiplying by 2k. Negative values of k correspond to shifting
bits right or dividing by 2|k|and rounding to the nearest
integer towards negative infinite. Any overflow bits are
truncated.
bitxor(a, b) Bit-wise XOR of integers a and b
swapbytes Swap byte ordering
2.7.1 Example
Create a script file, and type the following code −
a =5; b =7;
c = a + b
d = c +sin(b)
e =5* d
f =exp(-d)
This gives following result:
c = 12
d = 12.657
e = 63.285
f = 3.1852e-06
9|Page
structure C-like structures, each structure having named fields capable
of storing an array of a different dimension and data type
2.8.1 Example
Create a script file with the following code −
str='Hello World!'
n =2345
d =double(n)
un= uint32(789.50)
rn=5678.92347
c =int32(rn)
When the above code is compiled and executed, it produces the following result −
str = Hello World!
n = 2345
d = 2345
un = 790
rn = 5678.9
c = 5679
10 | P a g e
CHAPTER - 3
MATLAB –Vector and Matrix Operations
3.1 Vector Operations
A vector is a one-dimensional array of numbers. MATLAB allows creating two types
of vectors
Row vectors
Column vectors
MATLAB will execute the above statement and return the following result −
r =
7 8 9 10 11
11 | P a g e
When you reference a vector with a colon, such as v(:), all the components of the
vector are listed.
v =[1;2;3;4;5;6]; % creating a column vector of 6 elements
v(:)
MATLAB will execute the above statement and return the following result −
ans =
1
2
3
4
5
6
rv=[123456789];
sub_rv=rv(3:7)
MATLAB will execute the above statement and return the following result −
sub_rv =
3 4 5 6 7
a =[12345;23456;34567;45678]
MATLAB will execute the above statement and return the following result −
a =
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
12 | P a g e
Creating a matrix is as easy as making a vector, using semicolons (;) to separate the
rows of a matrix.
A = [1 2 0; 2 5 -1; 4 10 -1]
A =
1 2 0
2 5 -1
4 10 -1
... and then illustrate the fact that a matrix times its inverse is the identity matrix.
I = inv(A) * A
I =
1 0 0
0 1 0
0 0 1
MATLAB has functions for nearly every type of common matrix calculation.
13 | P a g e
There are functions to obtain eigenvalues...
eig(A)
ans =
3.7321
0.2679
1.0000
det(a)
ans =
-2
You can concatenate two matrices to create a larger matrix. The pair of
square brackets '[]' is the concatenation operator.
MATLAB allows two types of concatenations:
1. Horizontal concatenation
2. Vertical concatenation
Example
Create a script file with the following code:
a = [ 10 12 23 ; 14 8 6; 27 8 9]
b = [ 12 31 45 ; 8 0 -9; 45 2 11]
c = [a, b]
d = [a; b]
14 | P a g e
d =
10 12 23
14 8 6
27 8 9
12 31 45
8 0 -9
45 2 11
For example, to refer to the element in the 2nd row and 5thcolumn, of the
matrix a, as created in the last section, we type −
a =[12345;23456;34567;45678];
a(2,5)
MATLAB will execute the above statement and return the following result −
ans = 6
MATLAB will execute the above statement and return the following result −
v =
4
5
6
7
You can also select the elements in the mth through nth columns, for this we write −
a(:,m:n)
Let us create a smaller matrix taking the elements from the second and third columns
−
a =[12345;23456;34567;45678];
a(:,2:3)
MATLAB will execute the above statement and return the following result −
ans =
2 3
3 4
4 5
5 6
15 | P a g e
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
a =[12345;23456;34567;45678];
a(:,2:3)
MATLAB will execute the above statement and return the following result −
ans =
2 3
3 4
4 5
5 6
In the same way, you can create a sub-matrix taking a sub-part of a matrix.
For example, let us create a sub-matrix sa taking the inner subpart of a:
345
456
To do this, write −
a =[12345;23456;34567;45678];
sa= a(2:3,2:4)
MATLAB will execute the above statement and return the following result −
sa =
3 4 5
4 5 6
Now consider indexing into a matrix. We'll use a magic square for our experiments:
A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Most often, indexing in matrices is done using two subscripts—one for the rows and
one for the columns. The simplest form just picks out a single element:
A(2,4) % Extract the element in row 2, column 4
ans =
8
More generally, one or both of the row and column subscripts can be vectors:
A(2:4,1:2)
ans =
5 11
9 7
4 14
A single : in a subscript position is shorthand notation for 1:end and is often used to
select entire rows or columns:
A(3,:) % Extract third row
ans =
9 7 6 12
16 | P a g e
A(:,end) % Extract last column
ans =
13
8
12
1
There is often confusion over how to select scattered elements from a matrix.
For example, suppose you want to extract the (2,1), (3,2), and (4,4) elements from A.
The expression A([2 3 4], [1 2 4])won't do what you want. This diagram illustrates how
two-subscript indexing works:
17 | P a g e
The linear index of each element is shown in the upper left.
From the diagram you can see that A(14) is the same as A(2,4).
The single subscript can be a vector containing more than one linear index, as in:
A([6 12 15])
ans =
11 15 12
Consider again the problem of extracting just the (2,1), (3,2), and (4,4) elements of A.
You can use linear indexing to extract those elements:
A([2 7 16])
ans =
5 7 1
a =[12345;23456;34567;45678];
a(4,:)=[]
MATLAB will execute the above statement and return the following result −
a =
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
18 | P a g e
Next, let us delete the fifth column of a −
a =[12345;23456;34567;45678];
a(:,5)=[]
MATLAB will execute the above statement and return the following result −
a =
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
3.8.1 Example
In this example, let us create a 3-by-3 matrix m, then we will copy the second
and third rows of this matrix twice to create a 4-by-3 matrix.
a =[123;456;789];
new_mat=a([2,3,2,3],:)
new_mat =
4 5 6
7 8 9
4 5 6
7 8 9
19 | P a g e
CHAPTER - 4
MATLAB - Decision Making
4.1 If-else statements
Following is the general form of a typical decision making structure found in most of
the programming languages −
20 | P a g e
Example
a = 10;
% check the condition using if statement
if a < 20
% if condition is true then print the following
fprintf('a is less than 20\n' );
end
fprintf('value of a is : %d\n', a);
4.2 Loops
A loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the
programming languages −
MATLAB provides following types of loops to handle looping requirements. Click the
following links to check their detail −
Loop Type Description
while loop Repeats a statement or group of statements while a
given condition is true. It tests the condition before
executing the loop body.
for loop Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
nested loops You can use one or more loops inside any another loop.
21 | P a g e
4.2.1 For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.
for a =10:20
fprintf('value of a: %d\n', a);
end
22 | P a g e
MATLAB supports the following control statements.
Control Statement Description
break statement Terminates the loop statement and transfers execution
to the statement immediately following the loop.
continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
23 | P a g e
CHAPTER - 5 MATLAB – Plotting
5.1 Graph Plotting Commands
Command Purpose
Axis Sets axis limits.
Grid Displays gridlines.
Plot Generates xy plot.
print Prints plot or saves plot to a file.
title Puts text at top of plot.
xlabel Adds text label to x-axis.
ylabel Adds text label to y-axis.
close Closes the current plot.
close all Closes all plots.
figure Opens a new figure window.
hold Freezes current plot.
legend Legend placement by mouse.
refresh Redraws current figure window.
set Specifies properties of objects such as axes.
subplot Creates plots in sub windows.
text Places string in figure.
bar Creates bar chart.
loglog Creates log-log plot.
polar Creates polar plot.
semilogx Creates semi log plot. (Logarithmic abscissa).
semilogy Creates semi log plot. (Logarithmic ordinate).
stairs Creates stairs plot.
stem Creates stem plot.
To plot the graph of a function, you need to take the following steps −
Define x, by specifying the range of values for the variable x, for which the
function is to be plotted
Define the function, y = f(x)
Call the plot command, as plot(x, y)
Following example would demonstrate the concept. Let us plot the simple function y
= x for the range of values for x from 0 to 100, with an increment of 5
Create a script file and type the following code −
24 | P a g e
x =[0:5:100];
y = x;
plot(x, y)
When you run the file, MATLAB displays the following plot −
Let us take one more example to plot the function y = x2. In this example, we will draw
two graphs with the same function, but in second time, we will reduce the value of
increment. Please note that as we decrease the increment, the graph becomes
smoother.
Create a script file and type the following code −
x =[12345678910];
x =[-100:20:100];
y = x.^2;
plot(x, y)
When you run the file, MATLAB displays the following plot −
25 | P a g e
Change the code file a little, reduce the increment to 5 −
x =[-100:5:100];
y = x.^2;
plot(x, y)
26 | P a g e
5.3 Drawing Multiple Functions on the Same Graph
You can draw multiple graphs on the same plot. The following example
demonstrates the concept −
5.3.1 Example
Create a script file and type the following code −
x =[0:0.01:10];
y = sin(x);
g =cos(x);
plot(x, y, x, g,'.-'), legend('Sin(x)','Cos(x)')
MATLAB generates the following graph −
27 | P a g e
5.4 Setting Colors on Graph
MATLAB provides eight basic color options for drawing graphs. The following table
shows the colors and their codes −
Code Color
W White
K Black
B Blue
R Red
C Cyan
G Green
M Magenta
Y Yellow
5.4.1 Example
Let us draw the graph of two polynomials
x =[-10:0.01:10];
y =3*x.^4+2* x.^3+7* x.^2+2* x +9;
g =5* x.^3+9* x +2;
plot(x, y,'r', x, g,'g')
28 | P a g e
When you run the file, MATLAB generates the following graph −
When you run the file, MATLAB generates the following graph −
29 | P a g e
5.6 Generating Sub-Plots
When you create an array of plots in the same figure, each of these plots is
called a subplot. The subplot command is used for creating subplots.
Syntax for the command is −
subplot(m, n, p)
Where, m and n are the number of rows and columns of the plot array
and p specifies where to put a particular plot.
Each plot created with the subplot command can have its own characteristics.
Following example demonstrates the concept –
5.6.1 Example
Let us generate two plots −
y = e−1.5xsin(10x)
y = e−2xsin(10x)
When you run the file, MATLAB generates the following graph −
30 | P a g e
CHAPTER - 6 MATLAB – Graphics
This chapter will continue exploring the plotting and graphics capabilities of MATLAB.
We will discuss −
Drawing bar charts
Drawing contours
Three dimensional plots
When you run the file, MATLAB displays the following bar chart −
31 | P a g e
6.2 Drawing Contours
A contour line of a function of two variables is a curve along which the function
has a constant value. Contour lines are used for creating contour maps by joining
points of equal elevation above a given level, such as mean sea level.
MATLAB provides a contour function for drawing contour maps.
6.2.1 Example
Let us generate a contour map that shows the contour lines for a given
function g = f(x, y). This function has two variables. So, we will have to generate two
independent variables, i.e., two data sets x and y. This is done by calling
the meshgrid command.
The meshgrid command is used for generating a matrix of elements that give the
range over x and y along with the specification of increment in each case.
Let us plot our function g = f(x, y), where −5 ≤ x ≤ 5, −3 ≤ y ≤ 3. Let us take an
increment of 0.1 for both the values. The variables are set as −
[x,y]=meshgrid(–5:0.1:5,–3:0.1:3);
When you run the file, MATLAB displays the following contour map −
32 | P a g e
Let us modify the code a little to spruce up the map
[x,y]=meshgrid(-5:0.1:5,-3:0.1:3);%independent variables
g = x.^2+ y.^2;%ourfunction
[C, h]= contour(x,y,g);% call the contour function
set(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)
print-depsgraph.eps
When you run the file, MATLAB displays the following contour map −
When you run the file, MATLAB displays the following 3-D map −
33 | P a g e
You can also use the mesh command to generate a three-dimensional surface.
However, the surf command displays both the connecting lines and the faces of the
surface in color, whereas, the mesh command creates a wireframe surface with
colored lines connecting the defining points.
34 | P a g e
CHAPTER - 7 MATLAB – Functions
A function is a group of statements that together perform a task. In MATLAB,
functions are defined in separate files. The name of the file and of the function should
be the same.
Functions operate on variables within their own workspace, which is also called
the local workspace, separate from the workspace you access at the MATLAB
command prompt which is called the base workspace.
Functions can accept more than one input arguments and may return more than one
output arguments.
Syntax of a function statement is –
function[out1,out2,...,outN]=myfun(in1,in2,in3,...,inN)
7.1 Example
The following function named mymax should be written in a file
named mymax.m. It takes five numbers as argument and returns the maximum of
the numbers.
Create a function file, named mymax.m and type the following code in it −
function max =mymax(n1, n2, n3, n4, n5)
%Thisfunction calculates the maximum of the
% five numbers given as input
max= n1;
if(n2 > max)
max= n2;
end
if(n3 > max)
max= n3;
end
if(n4 > max)
max= n4;
end
if(n5 > max)
max= n5;
end
The first line of a function starts with the keyword function. It gives the name
of the function and order of arguments. In our example, the mymax function has five
input arguments and one output argument.
The comment lines that come right after the function statement provide the
help text. These lines are printed when you type −
helpmymax
35 | P a g e
MATLAB will execute the above statement and return the following result −
This function calculates the maximum of the
five numbers given as input
MATLAB will execute the above statement and return the following result −
ans = 89
36 | P a g e
Primary functions can be called from outside of the file that defines them,
either from command line or from other functions, but sub-functions cannot be called
from command line or other functions, outside the function file.
Sub-functions are visible only to the primary function and other sub-functions
within the function file that defines them.
7.3.1 Example
Let us write a function named quadratic that would calculate the roots of a
quadratic equation. The function would take three inputs, the quadratic co-efficient,
the linear co-efficient and the constant term. It would return the roots.
The function file quadratic.m will contain the primary function quadratic and the sub-
function disc, which calculates the discriminant.
Create a function file quadratic.m and type the following code in it −
function[x1,x2]= quadratic(a,b,c)
%thisfunction returns the roots of
% a quadratic equation.
%It takes 3 input arguments
% which are the co-efficients of x2, x and the
%constant term
%It returns the roots
d =disc(a,b,c);
x1=(-b + d)/(2*a);
x2=(-b - d)/(2*a);
end%end of quadratic
MATLAB will execute the above statement and return the following result −
ans = 0.7321
37 | P a g e
B(p2)
function y = B(p3)
...
end
...
end
7.4.1 Example
Let us rewrite the function quadratic, from previous example, however, this
time the disc function will be a nested function.
Create a function file quadratic2.m and type the following code in it −
function[x1,x2]= quadratic2(a,b,c)
function disc % nested function
d =sqrt(b^2-4*a*c);
end%end of function disc
disc;
x1=(-b + d)/(2*a);
x2=(-b - d)/(2*a);
end%end of function quadratic2
You can call the above function from command prompt as −
quadratic2(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205
38 | P a g e
%It takes 3 input arguments
% which are the co-efficient of x2, x and the
%constant term
%It returns the roots
d =disc(a,b,c);
x1=(-b + d)/(2*a);
x2=(-b - d)/(2*a);
end%end of quadratic3
You can call the above function from command prompt as −
Quadra c3(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.73205
39 | P a g e