Lab Tasks
Lab Tasks
Lab Tasks
Introduction to MATLAB
Exercise Objective:
PART A: Familiarization with MATLAB screen
Requirements:
A Computer
MATLAB
Theory:
MATLAB is a high performance language for technical computing. It integrates computation,
visualization and programming in an easy-to-use environment where problems and solutions are
expressed in familiar mathematical notation. It is particularly convenient for modeling,
simulation, analysis and design of dynamic systems.
The purpose of this introductory lab is to give you a quick introduction to MATLAB enabling
you to use the software from the very beginning of the Signal & Systems course. To run
MATLAB, double-click on the MATLAB icon. Once the program is loaded you will see the
prompt”>>” in the command window. The command window is the main window in which we
communicate with the MATLAB interpreter. Anything typed after “%” sign is treated as a
comment and ignored by MATLAB. First, we will familiarize with the MATLAB screen.
Procedure:
1
MATLAB has the following basic window components:
2
MATLAB Editor/Debuger Window
• Provides the same functionality found in most programming language development
environments
- Color codes MATLAB built-in functions (blue color)
- Easy access to cut, paste, print, and debug operations
- Checks balance in MATLAB function syntax
3
MATLAB Workspace
As you develop and execute models in MATLAB the workspace stores all variables names and
definitions for you. All variables are usually available to you unless the workspace is clear with
the ‘>>clear’ command
Getting Started:-
If you don’t know anything about MATLAB, then MATLAB help is the best way to learn about
something. In the command window of MATLAB simply write ‘help’;
>> help
It will display list of all toolboxes included in MATLAB. Then by investigating the name of
toolbox or the name of a function, which you would like to learn how to use, use the ‘help’
command:
>> help function name
This command displays a description of the function and generally also includes a list of related
functions. If you cannot remember the name of the function, use the ‘lookfor’ command and the
name of some keyword associated with the function:
>>look for keyword
This command will display a list of functions that include the keyword in their descriptions.
MATLAB also contains a variety of demos that can be with the ‘demo’ command.
MATLAB as a calculator
>>1+2*3 >>(1+2)*3
Ans = 7 ans = 9
Order of precedence is from left to right and from inner most parenthesis to outermost
4
Declaring and assigning a variable in MATLAB
Variable name=value(or expression)
Default variable is and
Let x=1;
Y=3*x
Y=3
Suppressing output:
If you simply type a statement and press Return or Enter, MATLAB automatically displays the
results on screen. However, if you end the line with a semicolon, MATLAB performs the
computation but does not display any output. This is particularly useful when you generate large
matrices
Complex Numbers:
MATLAB also supports complex numbers.The imaginary number is denoted with the symbol I
or j. There are different methods to declare a complex number which are given below
>>com=4+2i
com=4.0000 + 2.0000i
>> c=complex(1,-2)
Operations on Complex Numbers:
c=1.0000-2.0000i
Conjugate: Imaginary Part:
5
Built-in Mathematical functions in MATLAB
MATLAB comes with a large number of built-in functions that operate on matrices on an
element-by element basis. These include
sine sin
cosine cos
tangent tan
inverse sine asin
inverse cosine acos
inverse tangent atan
exponential exp
natural logarithm log
common logarithm log10
square root sqrt
absolute value abs
signsignum
o clc
o clear all
o clear x
o clear x,y
o clear(‘x’)
o close all
o who
o whos
o disp
o &
o &&
6
o |
o ||
o ~=
o ==
o <, >, <=, >=
For Loop:
x= i * i
end
While Loop:
This loop is used when the number of passes is not specified. The looping continues
as long as stated condition is satisfied. The while loop has the form:
while expression
statements
end
e.g x=1
while x <= 10
x = 3*x
end
Note: Other control statements include break, continue, return, switch… etc. Every student
should be able to use all these control statements.
>> v= 1:3:10
>>for j=1:4,
V (j) =j;
end
Output:
7
Task 2: Write down the result of the following While Loop.
j= 1 ;
w h ile ( j< = 4 )
a (j)= 1 0 * j;
j= j+ 1 ;
end
a
Output
Task 3: Comment on the below line of code and write the output.
a = 1 :1 0
i= 1 ;
w h ile (i< = 1 0 )
b (i)= 2 ^ a (i);
i= i+ 1 ;
end
b
Task 4: Write a program for the Table of 5 that will start in reverse order i.e., 5*10 to 5*1
8
Task 5: Write a program that will generate following outputs. Hint(cumsum)
Program1:
Program2:
9
Program3:
Program4:
To end a session
>>exit or quit
Conclusion:
10
Rubrics
Experiment 1:
Marks 5 4 3 2 1
11
Experiment 02
Introduction to Matrices and Arrays
Exercise Objective:
To become familiar with matrices, arrays, and operations that can be performed on them.
Requirements:
Intel based computer
MATLAB
Theory:
MATLAB stores variables in the form of matrices, which are M ×N, where M is the number of
rows and N the number of columns. A 1 × 1 matrix is a scalar; a 1 × N matrix is a row vector,
and M×1 matrix is a column vector. You can enter matrices into MATLAB in several different
ways:
• Enter an explicit list of elements.
Unit Matrix
The n × n identity matrix is a matrix of zeros except forhaving ones along its leading diagonal
(top left to bottom right). This is called eye (n) in MATLAB
12
>>a(1,3) = 3 % Assigning a value
A=
0 0 3 0
0 0 0 0
0 0 0 0
0 0 0 0
>>a=eye(3)
A= 1 0 0
0 1 0
0 0 1
Diagonal matrix
A diagonal matrix is similar to the identity matrix except that its diagonal entries are not
necessarily equal to 1.
>>d=[1 4 7];
>>D=diag(d)
D=
1 0 0
0 4 0
0 0 7
Generating vectors
Vectors can be generated using the ‘:’ command. For example, to generate a vector x that takes
on the values 0 to 10 in increments of 0.5, type the following which generates a 1×21 matrix
>> x = [0:0.5:10];
Other ways to generate vectors include the commands: ‘linspace’ which generates a vector by
specifying the first and last number and the number of equally spaced entries between the first
and last number, and ‘logspace’ which is the same except that entries are spaced logarithmically
between the first and last entry
13
Arithmetic matrix operations
The basic arithmetic operations on matrices (and of course scalars which are special cases
of matrices) are:
+ addition
- subtraction
* multiplication
/ right division
\ left division
^ exponentiation (power)
’ conjugate transpose
Note :An error message occurs if the sizes of matrices are incompatible for the operation.
The difference between matrix multiplication and element-by-element multiplication is
seen in the following example
>>A = [1 2; 3 4]
A=
12
34
>>B=A*A
B=
7 10
15 22
>>C=A.*A
C=
14
9 16
The magic Function
MATLAB actually has a built-in function that creates magic squares of almost any size. Not
surprisingly, this function is named magic:
B = magic (4)
14
B=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
sum(A)
MATLAB replies with
ans =
34 34 34 34
A'
Produces sum of rows
ans =
16 5 9 4
3 10 6 15
2 11 7 14
13 8 12 1
and
sum(A')'
produces a column vector containing the row sums
ans =
34
34
34
34
The sum of the elements on the main diagonal is obtained with the sum and the diag functions:
diag(A)
produces
ans =
16
10
7
1
15
and
sum(diag(A))
produces
ans =
34
Note: A matrix can be inverted if and only if its determinant is nonzero: If you try to compute the
inverse for a matrix with non-zero determinant you will get a warning message:
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate.
>>det(B);
Arrays
When they are taken away from the world of linear algebra, matrices become two-dimensional
numeric arrays. Arithmetic operations on arrays are done element by element. This means that
addition and subtraction are the same for arrays and matrices, but that multiplicative operations
are different. MATLAB uses a dot, or decimal point, as part of the notation for multiplicative
array operations.
The difference between matrix multiplication and element-by-element multiplication is
seen in the following example
>>A = [1 2; 3 4]
A=
12
34
>>B=A*A
B=
7 10
15 22
>>C=A.*A
C=
14
9 16
16
Cell:
A cell array is a data type with indexed data containers called cells, where each cell can contain
any type of data. Cell arrays commonly contain either lists of text, combinations of text and numbers, or
numeric arrays of different sizes.
cell{1}=rand(4,6)
Task 1: Comment on the below line of code and also write the output.
C = {1,2,3;'text',rand(2,3,2),{11; 22; 33}}
Task 2: Run the magic(3,4) command and also write the output of it. If Error occur,
explain its reason?
Task 3: What does the following commands do? If A is vector and Matrix
o max(A)
17
o min(A)
o diff(A)
o sum(A)
o sum(sum(A))
o v(1:3)
o v(3: end)
o v(:)
o v(3,3) = 0
o A(2,:)
o A(:,2:3)
o linspace(a,b,n)
o rand(a,b)
o round(x)
o ceil(x)
o floor(x)
o fix(x)
o a=randi(2,4)
o a=randi(2,4,23)
o a=randi([1 10],2,6)
o length(a)
o size(a)
o ones(a,b)
o zeros(a,b)
o b=cumsum(a)
o b=cumsum(a,1)
o b=cumsum(a,1,’reverse’)
o b=cumsum(a,2)
o b=cumsum(a,2,’reverse’)
18
Task5: Explain the output of the following commands?
A = [1 2 3; 4 5 6; 7 8 9]
Conclusion:
19
Rubrics
Experiment 2:
Marks 5 4 3 2 1
20
Experiment 03
Introduction to MATLAB
Exercise Objective:
PART A: Dealing with Polynomials & Partial Fraction Expansion
PART B: Derivation and Integration of a Function
PART B: Plotting in MATLAB
PART C: Solving ordinary differential equations (ODE) symbolically
Requirements:
Intel based computer
MATLAB
Theory:
MATLAB provides a full programming language that enables you to write a series of MATLAB
statements into a file and then executing them into a single document.
Polynomials are used for the analysis of transfer function because in case of transfer function we
want to see output and input in the form of polynomial. So it is important to study the
polynomials in MATLAB.
When trying to find the inverse Laplace transform (or Z transform) it is helpful to be able to
break a complicated ratio of two polynomials into forms that are on the Laplace transform or Z
transform table. We will illustrate here using Laplace transforms. This can be done using the
method of Partial fraction expansion (PFE) which is the reverse of finding a common
denominator and combining fractions. It is possible to do PFE by hand also. We will illustrate
hand computation only for the simplest case when there are no repeated roots and the order of
the numerator polynomial is strictly less than the order of denominator polynomial.
The primary tool we will use for plotting in MATLAB is plot().The MATLAB environment
provides a wide variety of techniques to display data graphically.
The type of graph you choose to create depends on the nature of your data and what you want to
reveal about the data. You can choose from many predefined graph types, such as line, bar,
histogram, and pie graphs as well as 3-D graphs, such as surfaces, slice planes, and streamlines.
After you create a graph, you can extract specific information about the data. You can also edit
graph components as well as annotate graphs. Annotations are the text, arrows, callouts, and
other labels added to graphs to help viewers see what is important about the data. Lastly you can
print your graph on any printer connected to your computer.
21
Though MATLAB is primarily a numeric package, it can certainly solve straightforward
differential equations symbolically as well using Math symbolic toolbox as demonstrated in this
lab.
Procedure:
PART A: Dealing with Polynomials
Polynomials
Polynomials arise frequently in systems theory. MATLAB represents polynomials as row vectors
of polynomial coefficients. For example, the polynomial s2 +4s−5 is represented in MATLAB
by the polynomial >> p = [1 4 -5]. The following is a list of the more important commands for
manipulating polynomials.
roots(p) Express the roots of polynomial p as a column vector
polyval(p,x) Evaluate the polynomial p at the values contained in the vector x
conv(p1,p2) Computer the product of the polynomials p1 and p2
deconv(p1,p2) Compute the quotient of p1 divided by p2
poly2str(p,’s’) Display the polynomial as an equation ins
Declaring a Polynomial: Automatic declare the Polynomial=x^3+x+3
>> coeffs(poynomial)
pol3=flipud(poly)
R=roots(pol3)
Roots of Polynomial:
Division of two Polynomials
>> rt_pol1=roots (pol1)
>>num=[2 5 4 6 4];
rt_pol1 =
>>den=[6 66 35 2];
-1.0000 + 1.7321i
>> [q r]=deconv(num,den)
-1.0000 - 1.7321i
q=
Determining Coefficients from given Roots:
0.3333 -2.833
>> c=poly(rt_1)
r=
>> c=poly(rt_pol1)
0 0.0000 179.3333 104.5000 9.6667
c = 1.0000 2.0000 4.0000
Integration of Polynomial Function
Finding value of Polynomial at a given point:
>> pol1=[1 2 4];
>> h=polyder(pol1) j = 4 18 40 32
h= 2 2
Multiplication of two Polynomials:
>> g=conv(pol1,pol2)
g=
1 6 20 32 32
23
Determine value of polynomial at given instant using Matlab
Task: x^5+2x^4-3x^3+7x^2-5x+7 at x=2
>> [r ,p, k]=residue(num1,den1) % r is the vector of PFE coefficients is the vector of roots of
den1 and k=0 if the degree of num1 < degree of den1
r=
-1.0000
-1.0000
24
2.0000
p=
-3.0000
-2.0000
-1.0000
k=
[]
Task: s + 3/s^3 + 5s + 4
y=x^2 +x+4
solve(y,x)
Derivative of an Equation
diff(y,x)
25
Integration of an Equation
int(y,x)
F1= ∑10
𝑘=0
𝑘^2
Matlab Code
symsum(k^2,k,0,10)
Task: Write the output and Matlab Code for the following series
∑5𝑘=1 1/𝑘^2
∑5𝑘=0 𝑘^2
∑5𝑚=0 𝑚𝑘^2
26
∑xk where k=1,2,3…5
Functions:
Syntax= function [Inputs]= my_function_name(Outputs)
Matlab Program for Summation and Multiplication of variables using function
Function [a,b]=myfunc(x,y,z)
a=x+y+z
b=x*y*z
end
max_val= -inf
for i=1:size(v)
if v(i)>max_val
max_val=v(i)
max_loc=i
end
end
27
Task: Find the Area of Sine wave from 0 to pi using function
28
can also edit graph components as well as annotate graphs. Annotations are the text, arrows,
callouts, and other labels added to graphsto help viewers see what is important about the
data.lastly you can print your graph on any printer connected to your computer.Annotations can
be added from the Insert menu like labels,titles,legend,line,arrows,text arrow,double arrow,text
box,rectangle,ellipse,axes,light etc.
Customization of plots
There are many commands used to customize plots by annotations, titles, axes labels, etc.
29
xlabel
ylabel
title
grid
gtext
text
axis
figure
figure(n)
hold on
hold off
grid on
grid off
close(n)
subplot(a,b,c)
orient
30
Multiple Plots in same Figure
t = 0:0.1:20;
y1 = sin(t);
y2=cos(t)
plot(t,y1,'-r*',t,y2,'b+')
m magenta * star
r red s square
w white d diamond
^ triangle (up)
triangle (right)
p pentagram
h hexagram
For example, plot (X,Y, ‘g:’) plots a green dotted line and plot(X,Y,’rd’) plots red diamond at
each data point. You may also edit colors and line styles directly from the menus which appear at
the top of the figure windowThe default is to plot solid lines. A solid white line isproduced by
>>plot (x, y, ’w-’)
31
The third argument is a string whose first character specifies the colour (optional) and the second
the line style.
Multi–plots:-
Several graphs can be drawn on the same figure as:
>>plot (x, y, ’w-’, x, cos (2*pi*x), ’g--’)
A descriptive legend may be included with
>>legend (’Sin curve’, ’Cos curve’)
Which will give a list of line–styles, as they appeared in the plot command, followed by a brief
description. MATLAB fits the legend in a suitable position, so as not to conceal the graphs
whenever possible. For further information do help plot etc. The result of the commands
>>plot (x, y, ’w-’, x, cos (2*pi*x), ’g--’)
>>legend (’Sin curve’, ’Cos curve’)
>>title (’Multi-plot ’)
>>xlabel (’x axis’), ylabel (’y axis’)
>>grid
Hold:-
A call to plot clears the graphics window before plotting the current graph. This is not
convenient if we wish to addfurther graphics to the figure at some later stage. To stop the
window being cleared:
>>plot (x, y, ’w-’), hold
Subplot:-
The graphics window may be split into an m × n array of smaller windows into which we may
plot one or more graphs. The windows are counted 1 to mn row–wise, starting from the top left.
Both hold and grid work on the current subplot.
>>subplot (221), plot (x,y)
>>xlabel (’x’), ylabel (’sin 3 pi x’)
>>subplot (222), plot (x, cos (3*pi*x))
>>xlabel (’x’), ylabel (’cos 3 pi x’)
>>subplot (223), plot (x, sin (6*pi*x))
>>xlabel (’x’), ylabel (’sin 6 pi x’)
>>subplot (224), plot (x, cos (6*pi*x))
>>xlabel (’x’), ylabel (’cos 6 pi x’)
subplot(221) (or subplot(2,2,1)) specifies that the window should be split into a 2 × 2 array and
we select the first subwindow.
32
Controlling Axes:-
If it is desired to plot a curve in a region specified by r = [x-min x-max y-min y-max]. Enter the
command axis(r). This command sets the scaling to the prescribed limits. Find-out more about
the command “axis” by typing:
help axis
If you wish to plot cos(t) of exercise 5 from time 0 to 10 seconds, and if you wish that the y-axis
should be from –2 to 2, then enter the following command:
axis([0 10 -2 2])Once a plot has been created in the graphics window you may wish to change
the range of x and y values shown on the picture
Property Editor
Figure properties can be changed interactively using thefollowing commands:
• PlotEdit
Allows interactive changes to plots (add legend, lines, arrows, etc.)
• PropEdit
Allows changes to all Handle Graphic properties in a MATLAB plot
Examples in Plotting
Example: Draw graphs of the functions
Task: y = sin(x)/x
33
Task: u= (1/(x-1)2)+x
Task: v= (x2+1)/(x2-4)
34
PART C: Solving ordinary differential equations (ODE) symbolically
MATLAB has a command dsolve that solves ordinary differential equations (ODEs)
symbolically.One form of the dsolve command is
dsolve(‘ODE’,’initial conditions’)
In the ODE string,D is used to represent the first derivative and Dn represents the nth derivative.
Example
To solve the differential equation y’(t) = ay(t) subject to the initial conditions y(0)=c and assign
the solution to y,one give the commands
>>syms a c
>> y=dsolve('Dy=a*y','y(0)=c')
y =c*exp(a*t)
35
Task: Y”(t) = -2y’(t) – y(t) at y(0) = 1 & y’(0) = 0
Task: Plot the sin, cosine and tan function in one window using different color and marker
Conclusion:
36
Rubrics
Experiment 3:
Marks 5 4 3 2 1
37