0% found this document useful (0 votes)
206 views119 pages

Signal and System Manual

The document provides an overview of MATLAB and its use for signals and systems applications. It describes MATLAB commands, plotting functions, and matrix operations. The lab manual includes 13 experiments for students to learn about signals and systems concepts using MATLAB, including signal plotting, transforms, and simulations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
206 views119 pages

Signal and System Manual

The document provides an overview of MATLAB and its use for signals and systems applications. It describes MATLAB commands, plotting functions, and matrix operations. The lab manual includes 13 experiments for students to learn about signals and systems concepts using MATLAB, including signal plotting, transforms, and simulations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 119

STUDENT MANUAL

For the Course


EE-311
Signals and Systems
5th Semester
(B.Sc Electrical Engineering)

Submitted To:
Engr. Kiran Arshad
Submitted By:
Muhammad Abdullah
BEEF18M032

Electrical Engineering Department,


College of Engineering and Technology (UCET)
University of Sargodha, Sargodha.
Course Title: Signals and Systems lab
Pre-requisite(s) None

Credit Hours 1

Contact Hours 3

Course Objectives:

 To introduce the concepts of signals and systems using MATLAB.

Programs Learning Outcomes:


PLO-1: Engineering Knowledge

PLO-5: Modern Tool Usage

PLO-9: Individual/Team Work

Course Learning Outcomes:


Upon successful completion of this lab, students will be able to:

CLO-1: To implement, perform and verify the basic MATLAB graphics, theorems, signals
systems and transforms on MATLAB software.

CLO-2: Depict the results of experiments in written and graphical format.

CLO-3: Respond as instructed while working in groups.

Mapping of CLOs to PLOs and Learning Domains:

Course Learning Program Learning Learning Domain Content


Outcome Outcome Weightage

CLO-1 PLO-5 Psychomotor 40%


(Level:P3)
CLO-2 PLO-1 Cognitive 40%
(Level: C3)
Affective 20%
CLO-3 PLO-9
(Level: A2)
List of Experiments
Sr.
Experiment Title
No

1 Demonstrating the use of MATLAB and perform Signal Plotting.

2 Demonstrate the use of MATLAB Graphics and Implementation of Basic Signals in MATLAB.

3 Demonstration and implementation of loops and decision making in MATLAB.

4 Implementation of Time Shifting, Scaling, Reversal, and Even/Odd Signal Manipulation in


MATLAB.

5 Implementation of Laplace Transform and Partial Fraction in MATLAB.

6 Implementation of Moving Average System and Convolution in MATLAB (With and Without
Built in Command).
Implementation of Auto and Cross Correlation of signals in MATLAB.
7
(With and Without Built in Command)

8 Implementation and Verification of Discrete Time Fourier Transform in MATLAB.

9 Implementation and Verification of Periodicity and Harmonics of Periodic Signals in


MATLAB.

10 Demonstration of Simulink and Implementation of its building blocks for signal processing.

11 Implementation and Verification of Sampling Theorem in MATLAB.

12 Implementation of Sound Manipulation and Noise Reduction in MATLAB.

13 Verification of Z-Transformation and Related Functions in MATLAB.


Experiment # 01
Demonstrating the use of MATLAB and perform Signal Plotting
Objective:
This lab provides an introduction to MATLAB. The lab also provides tutorial of matrix
operations, script writing and plotting aspect of MATLAB from signals and system point of
view.
Apparatus:
PC having MATLAB software
Theory:
MATLAB (matrix laboratory) is a multi-paradigm numerical computing environment and fourth-
generation programming language. Developed by Math Works, MATLAB allows matrix
manipulations, plotting of functions and data, implementation of algorithms, creation of user
interfaces, and interfacing with programs written in other languages, including C, C++, Java,
Fortran and Python.
Although MATLAB is intended primarily for numerical computing, an optional toolbox uses the
MuPAD HYPERLINK "http://en.wikipedia.org/wiki/Computer_algebra_system"symbolic
engine, allowing access to symbolic computing capabilities. An additional package, Simulink,
adds graphical multi-domain simulation and Model-Based Design for dynamic and embedded
systems.
In 2004, MATLAB had around one million users across industry and academia MATLAB users
come from various backgrounds of engineering, science, and economics. MATLAB is widely
used in academic and research institutions as well as industrial enterprises. Matlab logo is shown
in Fig. 1.1 and MATLAB R2013a running on Windows 8 is shown in Fig. 1.2.

Fig. 1.1: MATLAB L shaped membrane logo


Fig. 1.2: MATLAB R2013a running on Windows 8
Developer(s) MathWorks
Initial release 1984; 30 years ago
Stable release R2014b / October 3, 2014;
Preview release None
Development
Active
status
Written in C, C++, Java, MATLAB
Operating
Cross-platform: Microsoft Windows, Linux, and Mac OS X
system
Platform IA-32, x86-64
Type Technical computing
Proprietary HYPERLINK
License "http://en.wikipedia.org/wiki/Commercial_software"commercial
software
Website MATLAB product page
MATLAB Commands
Command : Operation
% : This sign is used to declare comments
Clc : Clears command window
Syms : symbolic tool box
Math Operation
+ : For addition
- : For subtraction
/ : For right Division
\ : For left Division
* : For multiplication
^ : For power
Built-in Constant
pi : 3.14
i ,j : (-1)1/2
NaN : Not a number
ans : for execution
exp(x) : Exponential function
sqrt(x) : square root of x
Matlab commands to plot any graph is shown in Table 1.1.

Table 1.1: Matlab plotting commands


Plotting Curves:
plot (x,y) Generates a linear plot of the values of x
(horizontal axis) and y(vertical axis).
bar (x) Generate a plot of the values of x using a bar scale
for x
stem (x) Generate a plot of the values of x using in discreet
time
figure (n) Used in creation of multiple plot windows. place
this command before the plot() command, and the
corresponding figure will be labeled as “Figure n”
subplot (m, n, p) m by n grid of windows, with p specifying the
current plot as the path window
Relational Operators
There are six relational operators in MATLAB as shown in Table 1.2.
Table 1.2: Relational operators
Operator Meaning
< Less than
<= Less than or equal to
== equal to
>= greater than or equal to
> greater than
~= Not equal to

MATLAB COMMAND:
linspace (5,8)
RESULT:

MATLAB COMMAND:
eye (3,4)
RESULT:
1 0 0 0
0 1 0 0
0 0 1 0

Some other Matlab commands and their function are shown in Table 1.3.
Table 1.3: Matlab commands and their function

Commands Functions
Linspace Creates regularly spaced vector
Logspace Creates logarithmically spaced vector.
Length Computers number of elements
Eye Creates an identity matrix
Ones Creates an array of ones
Zeros Creates an array of ones. Zeros
Print Prints plot or saves plot to a file title
Xlabel Adds text label to x-axis.
Ylabel Adds text label to y-axis.
plot Generates xy plot
Loglog Create loglog plot
Semilog Create semilog plot

Lab Task
Task 1: Write a MATLAB function of your name that inputs two variables x and y. Call these
variables x and y in command window to plot the sine and cosine waves. (Range of x and y can
be from 0 to 2*pi).
Task 2: Write a MATLAB function that inputs two variables x and y. Call these variables x and
y in command window that performs the following operation x2+y2. (Use x=left digit of your
registration number and y=right digit of your registration number)
TASK 1:

TASK 2:
Conclusion
MATLAB (matrix laboratory) is a fourth-generation high-level programming
language and interactive environment for numerical computation,
visualization and programming.It allows matrix manipulations; plotting of
functions and data; implementation of algorithms; creation of user interfaces;
interfacing with programs written in other languages, including C, C++, Java,
and FORTRAN; analyze data; develop algorithms; and create models and
applications.

It has numerous built-in commands and math functions that help you in
mathematical calculations, generating plots, and performing numerical
methods.
…………………….

Comments
MATLAB is widely used as a computational tool in science and engineering
encompassing the fields of physics, chemistry, math and all engineering
streams. It is used in a range of applications including −

Signal Processing and Communications


Image and Video Processing
Control Systems
Test and Measurement
Computational Finance
Computational Biology
…………………
Experiment # 02
Demonstrate the use of MATLAB Graphics and Implementation of Basic
Signals in MATLAB.
Objective
This lab provides an introduction to line specification commands to alter line color, marker
symbol, marker style. The lab also provides an introduction to basic signals like unit step and
unit impulse signal and how they are made.
Apparatus
Pc having MATLAB
Theory
Graphics objects are the basic elements used to display graphs. When a plotting function is
called, MATLAB® creates the graph using various graphics objects, such as a figure window,
axes, lines, text, and so on. Each object has a fixed set of properties, which you can use to control
the behavior and appearance of the graph.
Common Graphics Objects
When you call a function to create a graph, MATLAB creates a hierarchy of graphics objects.
For example, calling the plot function creates the following graphics objects:
• Figure — Window that contains axes, toolbars, menus, and so on.
• Axes — Coordinate system that contains the object representing the data
• Line — Lines that represent the value of data passed to the plot function.
• Text — Labels for axes tick marks and optional titles and annotations.
Different types of graphs use different objects to represent data. Because there are many kinds of
graphs, there are many types of data objects. Some are general purpose, such as lines and
rectangles and some are highly specialized, such as legends etc. Plotting functions can return the
objects used to create the graph.
Example: The following statements create a graph and return the line object created by
the plot function:
x = 1:10;
y = x.^3;
h = plot(x,y)
Its output graph is shown below in Fig. 2.1.
Fig. 2.1: Plot command output graph
Use h to set the properties of the line object. For example, set its Color property.
h.Color = 'red';
Line properties can also be specified when calling the plotting function.
h = plot(x,y,'Color','red');
You can query the line properties to see the current value:
h.LineWidth
ans =
0.5000
Line Specification
Various line types, plot symbols and colors may be obtained with PLOT(X,Y,S) as shown in
Table 2.1, where S is a character string made from one element from any or all the following 3
columns:
Table 2.1: Line specifications
Line Style
This example shows how to create a plot using a dashed dot line. Add the optional line
specification, '-.', to the x,y pair.The general syntax is Plot(x,y,’linestyle’,….)
>> x = linspace(0,2*pi,50);
>> y = sin(x);
>> plot(x,y,'-.')
Output graph is shown below in Fig. 2.2.

Fig. 2.2: Line style


Plot command can also be used for multiple graphs like
x = linspace(0,2*pi,50);
>> y = sin(x);
>> z = cos(x);
>>plot(x,y,'-.',x,z,':')
Its output graph is shown below in Fig. 2.3.

Fig. 2.3: Multiple graph output


Line Colour
The general syntax is Plot(x,y,’linestylelinecolor’,….).
For example
>> plot(x,y,'-.r',x,z,':g')
Prints the first dashed dot line as red and second line as green. In the following graph shown in
Fig. 2.4, the line color is green for plus ‘+’ and black for diamond‘d’.

Fig. 2.4: Graph showing line colour


Line Markers
The general syntax is:
Plot(x,y,’linestylelinecolorlinemarker,….)
>> plot(x,y,'-gd',x,z,'--r.')
Its output is shown below in Fig. 2.5.

Fig. 2.5: Use of line marker

Legends
LEGEND(string1,string2,string3, ...) puts a legend on the current plot using the specified strings
as labels.
Add a legend to the graph identifying each data set using the legend function. Specify legend
descriptions in the order that you plot the lines.
x=0:0.1:2*pi;
y=sin(x)
z=cos(x)
plot(x,y,'-g.',x,z,'--r*')
legend('y=sin(x)','z=cos(x)')
Its output graph is shown below in Fig. 2.6.
Fig. 2.6: Use of legends in graph
Data Exploration
Display Data Values Interactively:
Data cursors enable you to read data directly from a graph by displaying the values of points you
select on plotted lines, surfaces, images, and so on. You can place multiple data tips in a plot and
move them interactively. If you save the figure, the data tips in it are saved, along with any other
annotations present.
Enabling Data Cursor Mode:
Once you have enabled data cursor mode, clicking the mouse on a line or other graph object
displays data values of the point clicked. Clicking elsewhere does not create or update data tips
as shown in Fig. 2.7.
Fig. 2.7: Graph showing data cursor
Using multiple data tips
• Use the following procedure to create multiple data tips.
• Enable data cursor mode from the figure toolbar. The cursor changes to a cross.
• Click on the graph to insert a data tip.
• Right-click to display the context menu. Select Create New Data tip.
• Click on the graph to place the second data tip. e way to annotate a number of points on a
graph.
Input Command
Input command gives the user the prompt in the text string and then waits for input from the
keyboard.
The input can be any MATLAB expression, which is evaluated, using the variables in the current
workspace, and the result returned in any variable e.g.
D = input('No of days')
Signal:
Signal is basically a pattern of variation of some form e.g. Electrical signals:
Voltages and currents in a circuit
Electrical representation of a signal is:

A = amplitude, peak deviation of function from zero.


F = frequency, number of oscillations (cycles) that occur each second of time.
ɷ= 2πf , the angular frequency, is the rate of change of the function argument in units of rad/sec.
Two types of signals are Continuous signals and Discrete signals.

Continuous Signal
Signals that vary continuously over specified range. They are represented by small parenthesis in
SNS. i.e x(t), y(t) etc.Represented by Amplitude, frequency and phase. In MATLAB, plot
command is used. Continous signal is shown in Fig. 2.8.
Fig. 2.8: Continuous signal
Discrete Signal
It represents discrete or discontinuous quantities. They are represented by large square brackets
in SNS. i.e. x[t], y[t] etc. They are represented by Amplitude and location of samples. In
MATLAB, stem command is used. Discrete signal is shown in Fig. 2.8.

Fig. 2.8: Discrete signal


Unit Step Signal
It is also called as Heaviside Step function. It is a discontinuous function whose value is zero for
negative argument and one for positive argument as shown below in Fig. 2.9.

Fig. 2.9a: Discrete domain Fig. 2.9b: Continuous domain


Matlab Code
N=input('Number of Samples = ');
n=-N:1:N
x=[zeros(1,N) 1 ones(1,N)]
stem(n,x)
xlabel('Time');
ylabel('Amplitude');
title('Unit Step');
Its output graph is shown in Fig. 2.10.

Fig. 2.10: Unit step signal graph


Unit Impulse Signal
A function δ[n] that has the value zero everywhere except at x = 0 where its value is infinitely
large in such a way that its total integral is 1. In signal processing it is referred to as the unit
impulse function and is shown below:

Fig. 2.11: Unit Impulse Signal


Matlab Code:
N=input('Number of Samples = ');
n=-N:1:N
x=[zeros(1,N) 1 zeros(1,N)]
stem(n,x);
xlabel('Time');
ylabel('Amplitude');
title(‘Unit Impulse');
Its output graph is shown below:

Fig. 2.11: Unit impulse graph


Exponential Signal
Exponential signals are of the form x(t)=Ceat
• If a>0, x(t) is increasing/growing function, if a<0, x(t) is decreasing/decaying function. If
t=0 then x(t)=C
Example: Plot the signal x(t)=3e0.4t and y(t)=2e-0.9t in the time interval -2≤ t ≤ 5.
Matlab Code:
t=-2:0.01:5;
x=3*exp(0.4*t);
y=2*exp(-0.9*t);
plot(t,x)
hold on
plot(t,y)
Its output is shown below in Fig. 2.12.
Fig. 2.12: Exponential function graph
Lab Task
Task 1: Create a function of your name ‘name(a,n)’ which acquires amplitude (a) and index
sequence (n) as a function argument and plots unit step u[n] and unit impulse δ[n] functions in
same window using subplot. All functions must have same amplitude value a and index range
[n].
Task 2: Write a MATLAB program to generate a sinusoidal sequence. x[n] = Acos( wn + φ )and
plot the sequence using the stem function. The input data specified by the user is the n, amplitude
A, the angular frequency w, and the phase φ where 0 < w <π and 0 < φ < 2 π.
Task 3: Write a MATLAB function with name expsignal(A,a) that generates and plots the real
exponential sequence given as x[n]= Aan Where A is the amplitude and n is the time indexing
value. Solve it for the following cases
Growing exponential when a>1
Decaying exponential when a<1
a=-1 and (iv) a=1
Observe the output and comment about them
Task 4: Plot each of the following signals in the interval 0 ≤ n ≤ 20:

TASK 1:
TASK 2:

TASK 3:
a=1
a>1

a<1
a=-1

TASK 4:
Comments
In this lab we studied introduction to line specification commands to alter line
color, marker symbol, marker style. The lab also provides an introduction to basic
signals like unit step and unit impulse signal and how they are made.
We studied line specification, line style, line color, line markers, legends , data
exploration,
input comman etc. And we wrote some basic matlab codes. Matlab is an
interpreted language for numerical computation. It allows one to perform
numerical calculations, and visualize the results without the need for complicated
and time consuming programming. Matlab allows its users to accurately solve
problems, produce graphics easily and produce code effeciently.

…………………………….
Conclusion
MATLAB is a tool for technical computing, computation and visualization in an
integrated environment. MATLAB is an abbreviation for MATrix LABoratory, so
it is well suited for matrix manipulation and problem solving related to Linear
Algebra, Modelling, Simulation and Control applications, etc.
…………………………….
Experiment # 03
Demonstration and Implementation of loops and decision making in
MATLAB

Objective
In this lab we will study about loops. Loops are concerned with the concept of iteration. There
are two most prominent types of loop in Matlab and these are for and while loop. In this lab we
will also study about the basic concept of conditional statement also called if-else statement.
Apparatus
PC having MATLAB
Theory
Much like C or FORTRAN we can use loop syntax to repeat a sequence of commands. However,
MATLAB is not efficient in executing loop operations. In other words, we can say that using
loops in MATLAB is very slow. There are two basic types of loops. Counted loops also called
‘for loop’ and Conditional loops also called ‘while loop’.
“For” LOOP:
The ‘for’ loop allow us to repeat certain commands. If you want to repeat some action in a pre-
determined way, you can use the ‘for’ loop. All of the loop structures in MATLAB are started
with a key word such as ‘for’ or while’ and they all end with the word ‘end’.
The ‘for’ loop will loop ground some statement, and you must tell MATLAB where to start and
where to end. Basically, you give a vector in the ‘for’ statement and MATLAB will loop through
for each value in the vector. The ‘for’ loop Matlab syntax is:
for var = start:end
commands;
end
Example 3.1:
>>for j=1:4,
j
end
Output:
j=
1
j=
2
j=
3
j=
4
Note: Once the MATLAB reads the ‘end’ statement, it will loop through and print out j each
time. For another example, if we define a vector and data want to change the entries, we can step
through and change each individual entry.
Example 3.2:
v= 1:3:10
for j=1:4,
v(j) =j;
end
Result: The output shows the values of vector v from1 to 10 with the space of 3.
Output:
v=
1 4 7 10
Important Note: Using loops in MATLAB are not efficient. Loops cause the programs to run
very slow. Always use some alternative way so that programs run fast.

Alternative approach for Example 2


v= 1:3:10;
j=1;
while (j<=4)
v(j)
end
Result: The output shows the values of vector v from1 to 10 with the space of 3.
Output:
v=
1 4 7 10
MATLAB provide us another efficient method to avoid from loops. That is its advantage over
other computer languages.
Example 3.3:
>>v=1:3:10
>>v (1:4) =1:4;
Result: The output of this code shows the number from 1 to 10 with the interval of 3 (i.e. 1 4 7
10).
Now here is another example of using ‘for’ loops this example declares a vector ‘x’ and then
uses a ‘for’ loop to sum all of the values in ‘x’.

Example 3.4:
clc
clear all
close all
x=20:20:200;
total =length(x);
temp=0;
for i=1:total
temp =temp+x(1);
temp
end

Result: init we define the vector x whose values are between 20 and 200 with the interval of 20
and the loop run length of x times and add the numbers and display it in the output.
Output:
x=
20 40 60 80 100 120 140 160 180 200
temp =
1100

Prescription:
In example 4 we define a vector ‘x’ with values,
x = [20 to 60 80 100 120 140 160 180 200]
then we use “total = length(x)”. In this statement we are calling the “length” function. This will
return the total number of elements in ‘x’ & assign it to the total variable. Then we define a
‘temp’ variable and set it to ‘o’, using “temp = 0” statement.
Then we use a ‘for’ loop & using this ‘for’ loop we add the x (i) value to temp and reassign that
value to temp again.
While LOOP:
The “while” loop repeats a sequence of commands as long as some condition is met. The while
loop Matlab syntax is:
while expression
commands;
end
Example 3.5:
j=1;
while(j<=4)
a(j)=10*j;
j=j+1;
end
a
Output:
a=
10 20 30 40
Result: The loop run four times and each time multiply the index with ten and display it in the
output.
The while loop continues to execute until the value of j becomes greater than 4. When this
happens the loop exits. The above ‘while’ loop body will execute until the condition “j < = 4”.
When this condition becomes false the ‘while’ loop will stop executing.
Example 3.6:
a=1:10
i=1;
while(i<=10)
b(i)=2^a(i);
i=i+1;
end
b
Output:
a=
1 2 3 4 5 6 7 8 9 10

b=
2 4 8 16 32 64 128 256 512 1024
Result: The loop will run less than or equal to 10 times, taking that number as the power of 2
find result and display it.
Description: The above example declares a vector
a = [1 2 3 4 5 6 7 8 9 10].
Then using a “while” and tells that loop until the value of ‘i’ is less than or equal to 10. Then
using the statement “b (i) = 2 a (i)” & “i = i + 1" it makes another vector having values.
b = [21 22 23 24 25 26 27 28 29 210] at the end it displays the value of ‘b’
IF Statement:
We can make decisions by using the ‘if’ statement. The ‘if’ must be terminated with an ‘end’
statement.
Example 3.7
c=2;
if(c==1)
disp('c is 1')
elseif (c==2)
disp('c is 2')
else
disp('c is neither 1 nor 2');
end
Output: c is 2
Result: init we use the if-else command and check the value of c.
The above example declares a variable ‘c’ & assigns it a value ‘2’ by using “c = 2”.
Then it uses ‘if’, if-‘else’ and ‘else’ statements to check the value of ‘c’ and displays the result
using “disp” command.
Joseph Fourier:
Joseph Fourier showed that any periodic signal could be represented by a series of sinusoidal
functions. The figure shows how odd harmonics of sine waves are added to give a square wave.

Example 3.8
Square wave
A square wave can be constructed from multiple sine waves at different frequencies. The sine
waves added in addition to the fundamental frequency are called harmonics; a square wave has
harmonics at odd multiples of the fundamental frequency. As higher harmonics are added, the
result gets closer to an ideal square wave, which contains infinite harmonics.

Example 3.9
Write a MATLAB code to generate a square wave having user defined amplitude… Use for loop
to add up the sine waves…
EXERCISE:
E.1. Define a vector a = [1 2 3 4 5] and then using a “for” loop create another vector ‘b’ haring
the following values corresponding to ‘a’.
E.2. Without using a “for” loop and using some alternative method define vector
a = [1 2 3 4 5] and create b1 = []
E.3. Indicate the error in the following. Tell the line # which contains the error and what is the
error.
1.......v=0:2:10
2.......for c=1:length(v)
3........ v(c-1)=v(c)+5;
4........end
5........v
E.4. Refer to the “example 4”. We have vector
x = [20 40 60 80 100 120 140 160 180 200] and we want to multiply all the elements of the
vector ‘x’ e.g. (20 x 40 x 60 …………. x 200) and store the result in temp. Modify the code for
“example 4” so that it performs the above task.
E.5. Refer to “example 6”. Change the code so that it creates vector ‘b’ having values
b = [51 52 53 …………. 510].
E.6. What will be the output of “example 7” if we define C = 3 and other code remains
unchanged?
Comments
The FOR loop is nicer and more compact, if the number of iterations is known
before the loop is started. The WHILE loop is nicer, when the number of
iterations is determined inside the loop. There are some overlaps, e.g. running
an iteration until a certain number of loops or a specific criterion is reached.
Then usually WHILE is preferred with the convergence limit as test, because
this reflects the main character of the loop, while the limitation of iterations is
a fallback mechanism only.
……………………….
Conclusion
In this lab we studied about For loop and While loop in Matlab.
we performeed some examples and got the results.

END
……………………….
Experiment # 04

Implementation of Time Shifting, Scaling, Reversal, and Even/Odd Signal


Manipulation in MATLAB

Objective
In this lab we will studied about the concept of time shifting, scaling and reversal and their
implementation. This lab also provide us introduction about the even and odd signal and their
manipulation. In this lab we will also study that a signal is the combination of even and odd
components and how we can break signal into even and odd component.
Apparatus
Pc having MATLAB
Theory
Signal Operations are simply modifications to the time variable of the signal to generate new
signals. These are pretty similar to the mathematical graphical transformations. The three kinds
of Signal Operations are Time Shifting, Time Scaling and Time reversal.
• Time shifting:
Time Shifting is simply shifting the signal in time. If a continuous time signal is defined as:
y(t) = x(t - to)
Then we can say that y(t) is the time shifted version of x(t).
• When to be greater than zero then signal shifts to the right and the signal obtained is
called delayed signal.
• When to be less than zero then signal shifts to the left and the signal obtained is called
advanced signal.
• Or we can define it as when we add a constant to the time, we obtain the advanced signal,
& when we decrease the time, we get the delayed signal.

For example: If we want to shift the signal then in MATLAB we can write the code as:
t=-10:0.01:10
f=0.1
to=2
tt=-2
x=sin(2*pi*f*t)
y=sin(2*pi*f*(t-to))
z=sin(2*pi*f*(t-tt))
subplot(311)
plot(t,x)
subplot(312)
plot(t,y)
subplot(313)
plot(t,z)
Its output graph is shown in Fig. 4.1.

Fig. 4.1: Time shifting


• Time scaling:
Time scaling of signals of signals involves the modification of a periodicity of the signal,
keeping its amplitude constant. Its mathematically expressed as, y(t) = x(at) Where, x(t)
is the original signal, and a is the scaling factor.
• If a > 1 implies, the signal is compressed
• If a < 1 implies, the signal is expanded.

Example: If we want to scale the signal then in MATLAB we can write the code as:
t=-10:0.01:10
f=0.1
a=1.5
x=sin(2*pi*f*t)
y=sin(2*pi*f*(a*t))
z=sin(2*pi*f*(t/a))
subplot(311)
plot(t,x)
title('orignal signal')
subplot(312)
plot(t,y)
title('compressed signal')
subplot(313)
plot(t,z)
title('expanded signal')
Its output is shown in Fig. 4.2.
Fig. 4.2: Time scaling

• Time reversal:
The reversing or flipping the time indexes is called flipping or time reversal.
We can define it as: y(t) = x(-t). in matlab for reversal we use the “fliplr” command.
Example
t=-10:0.01:10
f=0.1
a=1.5
x=sin(2*pi*f*t)
y=fliplr (x)
z=sin(2*pi*f*(-t))
subplot(131)
plot(t,x)
title('orignal signal')
subplot(132)
plot(t,y)
title('by builtin command')
subplot(133)
plot(t,z)
title('flipped signal')
Its output is shown in Fig. 4.3.
Fig. 4.3: Time reversal
Even signal
If a signal becomes equal to the flipped version of itself, it is called even signal. We can
mathematically define it as: x(t) = x(-t)
Odd signal
If the flipped version of the signal becomes equal to the signal that is amplitude scaled by -1,
then the signal is called odd signal. Mathematically we can define it as: x(-t) = -x(t).
Conventially any signal is the combination of even and odd component. We can break the break
the signal into its even and odd parts. The even part of a signal can be expressed:
Xe (t) = 1/ 2 [x(t) + x (−t)]
And the odd part of the signal can be expressed as:
Xo (t) = 1/ 2 [x (t) − x (−t)]

Task: Solve for whether the signal is even or odd or combination of both.
• Cos(2*pi*f*time)
• sinc(2*pi*f*time)
• square(2*pi*f*time)
• sin(2*pi*f*time) .* sinc(2*pi*f*time)
• cos(2*pi*f*time) .*square(2*pi*f*time)

CODE:
function k=lab4tasksns()
t=-10:0.01:10
f=0.1
x=cos(2*pi*f*t)
a=fliplr(x)
subplot(5,2,1)
plot(t,x)
title('original signal cos(2*pi*f*t)')
subplot(5,2,2)
plot(t,a)
title('reversed signal')
y=sinc(2*pi*f*t)
b=fliplr(y)
subplot(5,2,3)
plot(t,y)
title('original signal sinc(2*pi*f*t)')
subplot(5,2,4)
plot(t,b)
title('reversed signal')
z=square(2*pi*f*t)
c=fliplr(z)
subplot(5,2,5)
plot(t,z)
title('original signal z=square(2*pi*f*t)')
subplot(5,2,6)
plot(t,c)
title('reversed signal')
p=sin(2*pi*f*t).*sinc(2*pi*f*t)
q=fliplr(p)
subplot(5,2,7)
plot(t,p)
title('original signal sin(2*pi*f*t).*sinc(2*pi*f*t)')
subplot(5,2,8)
plot(t,q)
title('reversed signal')
m=cos(2*pi*f*t).*square(2*pi*f*t)
n=fliplr(m)
subplot(5,2,9)
plot(t,m)
title('original signal cos(2*pi*f*t).*square(2*pi*f*t)')
subplot(5,2,10)
plot(t,n)
title('reversed signal')

OUTPUT:
Task 1:
Take the values n = (-3 -2 -1 0 1) and x= (7 -6 5 0 -1); use plot command to get the continuous
shaped signal as shown below. Then write a MATLAB code to get the time reversed signal:
(i) by reversing n indexes (ii) by using fliplr command.
CODE:
function f=lab4sns()
n=[-3,-2,-1,0,1]
x=[7,-6,5,0,-1]
subplot(3,1,1)
plot(n,x)
title('Original continuos signal')
xlabel('time')
ylabel('amplitude')
z=[3,2,1,0,-1]
subplot(3,1,2)
plot(z,x)
title('Reverse signal by reversing indices of n')
xlabel('time')
ylabel('amplitude')
y=fliplr(n);
subplot(3,1,3)
plot(y,x)
title('Reverse signal by using fliplr')
xlabel('time')
ylabel('amplitude')

OUTPUT:
Task 2:
Let n = [-3 -2 -1 0 1 2]; x = [-7 5 -1 -4 4 3]; Use stem command to plot it in first window. Then
time scale (Compressed concept) this signal by 2. i.e x[2n] and plot the scaled signal in 2 nd
window. Also time scale this signal by x[n/2] and plot in 3rd window.
OUTPUT:
Comments
MATLAB can be used to perform shifting of signals. A signal can be delayed
as well as advanced.
The basic idea is to add the shift value to indices and thereby plotting the
signal.The inbuilt function fliplr() function can be used to perform
reversing or folding a signal.
Syntax:
fliplr(a) : if a is row vector it returns a vector with the same size of a but with
reversed order.
if a is column vector it flips the elements one column to the other.
Basic idea :
flip the elements
flip the indices with a ‘ – ‘ sign.
……………………………….
Conclusion
Time scaling of signals of signals involves the modification of a periodicity of
the signal, keeping its amplitude
constant. Its mathematically expressed as,
Y (t) = βX(t)
Where, X(t) is the original signal, and β is the scaling
factor. If β > 1 implies, the signal is compressed. And
if β < 1 implies, the signal is expanded.
Following example will help you understand the time
scaling property with the help of MATLAB’s has a builtin function tripuls to
generate a triangular pulse.
Experiment # 05
Implementation of Laplace Transform and Partial Fraction in MATLAB

Objective
In this lab we will study about partial fraction and Laplace transform. We will study about how
to represent them in MATLAB.
Apparatus
PC having MATLAB
Theory
Laplace Transform
Laplace transform will convert a function in some domain into a function in another domain,
without changing the value of the function. For example, let’s take this function where a Laplace
transform is used to convert a function of time to a function of frequency.
L {cos(wt)} = w / (s² + w²)
Why do we use Laplace Transform?
• We use Laplace transform to convert equations having complex differential equations to
relatively simple equations having polynomials. Since equations having polynomials are
easier to solve, we employ Laplace transform to make calculations easier.
• With Laplace transform nth degree differential equation can be transformed into an nth
degree polynomial. One can easily solve the polynomial to get the result and then change it
into a differential equation using inverse Laplace transform.
• The development of the logarithm was considered the most important development in
studying astronomy. In much the same way, the Laplace transform makes it much easier
to solve differential equations.
• The amazing thing about using Laplace transforms is that we can convert the whole ODE
initial value problem (I.V.P) into Laplace transformed functions of s, simplify the algebra,
find transformed solution F(s) the undo the transform to get back to the required solution f as
a function of t.
• If O.D.E is solved, particular and Homogeneous solutions are calculated separately but
LAPLACE finds both simultaneously.
• Normally, Homogeneous response is transient response and particular corresponds to steady
state. So, if solving in Time Domain, we first find time domain solution then apply initial
conditions but LAPLACE directly includes initial conditions.
• A Laplace transform is a type of integral transform. (Unilateral).
How to take the Laplace of functions in MATLAB:
• In MATLAB the command laplace is used.. While ilaplace is used for inverse of laplace..
Recall syms and pretty command from lab 01.
Example 5.1: Take the Laplace Transform of e^-t.

Output:

Partial Fraction
In algebra, the partial fraction decomposition or partial fraction expansion of a rational
function (that is, a fraction such that the numerator and the denominator are both polynomials) is
an operation that consists of expressing the fraction as a sum of a polynomial (possibly zero) and
one or several fractions with a simpler denominator.
The importance of the partial fraction decomposition lies in the fact that it
provides algorithms for various computations with rational functions, including the explicit
computation of anti-derivatives, Taylor series expansions, inverse Z-transforms, inverse Laplace
transforms.
Transfer function
A Transfer Function is the ratio of the output of a system to the input of a system, in the Laplace
domain considering its initial conditions and equilibrium point to be zero. If we have an input
function of X(s), and an output function Y(s), we define the transfer function H(s) to be:
There are two forms of transfer function representation in MATLAB. The most obvious is the
polynomial form where

It is entered as two row vectors with the polynomial coefficients entered in the order of
ascending powers of s.
>> b = [1, 2, 3]; >> a = [1, 4, 5, 6];
Missing coefficients must be entered as zero: so q(s) = s2 + 2s and r(s) = s4 + s2 + 1 are entered
as:
>> q = [1, 2, 0]; >> r = [1, 0, 1, 0, 1];

Zeros, poles and gain:


To find the zero, poles and gain of a transfer function from the vectors ‘num’ and ‘den’ which
contain the coefficients of the numerator and denominator polynomials type.
[z,p,k]= tf2zp(num,den)
The zeros are stored in z, poles are stored in p and the gain is stored in k. To find the numerator
and denominator polynomials from z, p and k type.
[num,den] =zp2tf (z,p,k)
And the residue command is used to find the partial fraction expansion or decomposition.
RESIDUE Partial-fraction expansion (residues).
[R,P,K] = RESIDUE(B,A) finds the residues, poles and direct term of a partial fraction
expansion of the ratio of two polynomials B(s)/A(s).
Example 5.2:
Find the solution of the polynomial equation given below.

MATLAB CODE:

OUTPUT:
Task 1: Find laplace and ilaplace of the following.
TASK 1:
Laplace Transform of each part is given in sequence with Code and Output
part 1
part 2;
part 3;
part 4;
part 5;
part 6;
part 7;
part 8;
part 9;
part 10;
part 11;
Task 2: Express the following in partial fraction form using residue command and also convert
back the partial fraction expansion to polynomial co-efficient.
Comments:
Most ordinary differential equations arising in science and engineering
applications cannot be solved easily or it takes too much time, Classical
methods may not be able to give solution. A transformations method can
be used to get an exact solution to a differential equation. There are many
methods which use transformation, Laplace transforms are commonly
used in solving mathematical and physical problems which contains
ordinary or partial differential equations with constant coefficients and
integral equations as those problems are arising in the many branches of
physics as electronic circuit analysis .But it takes too much time for
solving by hand and in papers, These ODE can be analyzed. However,
mathematical software’s was developed for solving the ordinary
differential equations easily in some seconds, To compute quickly the
solution of differential equation, One of such powerful and must know
software’s language is MATLAB language, which is easy to use, developed
by Mathworks
Conclusion:
Matlab program is contains Many easy to use tools,
programs and functions to solve or simulate differential equation by
Laplace transform and numerical methods such .In last decades
must of researcher developed new functions and programs for Matlab
program for solving and computing exact solution for ordinary differential
equations, developed functions estimated exact solution in some second
with graph of exact solution, which reduced too many time for
mathematicians and physicist in solving these problem by hand in paper.
……………………….
Signals and Systems (EE-311)

Experiment # 06
BEEF18M032
MUHAMMAD ABDULLAH
Implementation of Moving Average System and Convolution in MATLAB
(With and Without Built in Command)

Objective
This lab provides us introduction about the convolution and moving average system phenomena,
we will learn how to implement them in MATLAB with and without built in command.
Apparatus
PC having MATLAB

Theory
1. Moving average system
The moving average system can be defined by the equation as:

Moving average system take the succession of averages derived from successive segments
(typically of constant size and overlapping) of a series of values.
In simple words moving average system take the present value of the input and also by using
previous values according to the formula and calculate their average. The casual moving average
system can be represented as the cascade system.
Signals and Systems (EE-311)

2. Convolution
Convolution is the process used to find the response of a Linear Time Invariant system to a given
input, assuming we already know the impulse response of that system. The physical meaning of
the convolution is the multiplication of two signal functions. The convolution of two signals helps
to delay, attenuate and accentuate signals.
Simply we can that the convolution of one function (the input signal) with a second function
(the impulse response) gives the output of a linear time-invariant system (LTI). At any given
moment, the output is an accumulated effect of all the prior values of the input function, with the
most recent values typically having the most influence (expressed as a multiplicative factor). The
impulse response function provides that factor as a function of the elapsed time since each input
value occurred.
In case of continuous-time signals, we can find the system response using the Convolution Integral,
while in case of discrete-time systems; the response can be calculated using the Convolution Sum.
For example, let 𝑥1(𝑛) and 𝑥2(𝑛) be two discrete-time signals. The convolution sum of the two
signals can be calculated using the formula:

In convolution there are two sequences M and N if 𝑥1(𝑛) is a M- point sequence and 𝑥2(𝑛) is an
N – point sequence, then the convolved sequence, 𝑦(𝑛) is a (M+N-1) – point sequence.
We can perform the convolution by different methods:
● By using built-in command:
MATLAB has a built-in function called “conv” function, which basically performs a linear
convolution of any two given sequences.
● By using the Linear Convolution Sum formula:
In this method we use the convolution sum formula and substitute values of 𝑛 and 𝑘 in the
expression and calculate the values of the convolved signal. Alternatively, we can perform the
signal inversion-time shift-superposition method, by which we can calculate the resultant
signal values.
Signals and Systems (EE-311)

MATLAB CODE OF MOVING AVERAGE SYSTEM:

OUTPUT:
Signals and Systems (EE-311)

EXPLANATION:

 Step 1: Take an input signal and also define its length

 Step 2: Take an impulse response signal and defined its length

 Step 3: perform a convolution using a conv function on matlab

 Step 4: If we want to plot three signals we use a subplot and stem functions.

MATLAB CODE OF CONVOLUTION:

1. WITH BUILT IN COMMAND


Signals and Systems (EE-311)

OUTPUT:
Signals and Systems (EE-311)

EXPLANATION:

 Step 1: Take an input signal and also define its length

 Step 2: Take an impulse response signal and defined its length

 Step 3: perform a convolution using a conv function on matlab

 Step 4: If we want to plot three signals we use a subplot and stem functions.

2. Without Built In Command


Signals and Systems (EE-311)

OUTPUT:
Signals and Systems (EE-311)

EXPLANATION:

Comments:

A mathematical way of combining two signals to form a new signal is known as Convolution. In matlab
for convolution ‘conv’ statement is used. The convolution of two vectors, p, and q given as “a = conv( p,q
)” which represents that the area of overlap under the points as p slides across q. Convolution is the
most important technique in Digital Signal Processing. The direct calculation of the convolution can be
difficult so to calculate it easily Fourier transforms and multiplication methods are used. Convolution is
used in differential equations, statistics, image and signal processing, probability, language processing
and so on.

Conclusion:

For performing a convolution operation on matlab we follow following steps:-

 Step 1: Take an input signal and also define its length


Signals and Systems (EE-311)

 Step 2: Take an impulse response signal and defined its length

 Step 3: perform a convolution using a conv function on matlab

 Step 4: If we want to plot three signals we use a subplot and stem functions.
Signals and Systems (EE-311)

Experiment # 08
Implementation and Verification of Discrete Time Fourier Transform in
MATLAB

Objective
The objective of this lab is to understand the concept of Fourier series and implement it in
MATLAB.
Apparatus
PC having MATLAB

Theory
Time and Frequency Domain
● Time domain and frequency domain are two modes used to analyze data. Both time domain
analysis and frequency domain analysis are widely used in fields such as electronics,
acoustics, telecommunications, and many other fields.
● Frequency domain analysis is used in conditions where processes such as filtering, amplifying
and mixing are required.
● Time domain analysis gives the behavior of the signal over time. This allows predictions and
regression models for the signal.
● Frequency domain analysis is very useful in creating desired wave patterns such as binary bit
patterns of a computer.
● Time domain analysis is used to understand data sent in such bit patterns over time

Time Domain
Time domain analysis is analyzing the data over a time period. Functions such as electronic
signals, market behaviors, and biological systems are some of the functions that are analyzed
using time domain analysis. For an electronic signal, the time domain analysis is mainly based
on the voltage – time plot or the current – time plot. In a time domain analysis, the variable is
always measured against time. There are several devices used to analyze data on a time domain
basis. The cathode ray oscilloscope (CRO) is the most common device when analyzing
electrical signals on a time domain.
Signals and Systems (EE-311)

Tells us how properties (air pressure in a sound function, for example) change over time:

● Amplitude = 100
● Frequency = number of cycles in one second = 200 Hz

Frequency Domain
Frequency domain is a method used to analyze data. This refers to analyzing a mathematical
function or a signal with respect to the frequency. Frequency domain analysis is widely used
in fields such as control systems engineering, electronics and statistics. Frequency domain
analysis is mostly used to signals or functions that are periodic over time. This does not mean
that frequency domain analysis cannot be used in signals that are not periodic. The most
important concept in the frequency domain analysis is the transformation. Transformation is
used to convert a time domain function to a frequency domain function and vice versa.

■ Tells us how properties (amplitudes) change over frequencies:

Time-Frequency Analysis
■ A signal has one or more frequencies in it, and can be viewed from two different
standpoints: Time domain and Frequency domain

1. Time‐domain figure: how a signal changes over time


2. Frequency‐domain figure: how much of the signal lies within each given frequency band
over a range of frequencies
Signals and Systems (EE-311)

Why frequency domain analysis?

● To decompose a complex signal into simpler parts to facilitate analysis.

● Differential and difference equations and convolution operations in the time domain
become algebraic operations in the frequency domain.

● We can go between the time domain and the frequency domain by using a tool called
Fourier transform.

● A Fourier transform converts a signal in the time domain to the frequency domain
(spectrum).

● An inverse Fourier transform converts the frequency domain components back into the
original time domain signal.

Example:

Assume that we have a signal.

Then the DFT of the signal is a sequence X[k] for k=0… N-1.

Where N represents no. of points that are equally spaced in the interval 0 to 2pi. And the inverse
is then,
Signals and Systems (EE-311)

To perform the IDFT by:


•  using positive powers instead of negatives
•  Multiplying each component of the output by 1 / N
Hence the algorithm is the same but computational load increases due to N extra multiplications

Find the DFT of the sequence x[n]=[0 1 2 3]..


Signals and Systems (EE-311)

To find DFT using formula in MATLAB:


Signals and Systems (EE-311)

Output:

DFT in MATLAB
Signals and Systems (EE-311)

A fast Fourier transform (FFT) algorithm computes the discrete Fourier transform (DFT) of a
sequence, or its inverse. Fourier analysis converts a signal from its original domain (often time or
space) to a representation in the frequency domain and vice versa. The Fast Fourier Transform
does not refer to a new or different type of Fourier transform. It refers to a very efficient algorithm
for computing the DFT. The time taken to evaluate a DFT on a computer depends principally on
the number of multiplications involved. DFT needs N2 multiplications. FFT only needs Nlog2(N).

● Y=fft(X) computes the discrete fourier transform (DFT) of X using a fast fourier transform
transform algorithm.

● Y=fft(X,n) returns the n-point DFT. If no value is specified , Y is same size as X.

● ifft(X) function is used to compute the Inverse DFT.

MATLAB Code

Convolution in Frequency Domain


An interesting property of the Discrete Fourier Transforms, is the effect it has on convolution.
Convolution of two signals in the time domain translates to a multiplication of their Fourier
transforms in the frequency domain. For this, we find the discrete Fourier transforms of
the individual signals, multiply them, and apply an Inverse Fourier Transform upon the
product, to get the convolved signal in the time domain.

To plot the pz-map of transfer function:

● pzmap(sys) plots the pole-zero map of the continuous- or discrete-time LTI model sys.
● For SISO systems, pzmap plots the transfer function poles and zeros. The poles are plotted as
x's and the zeros are plotted as o's

Lab Tasks:

Task 1: Find the DFT of x=[2 4 -1 6] using Build-in command and also by summation formula
Signals and Systems (EE-311)

By built in Command

By Formula
Signals and Systems (EE-311)

Task 2: Perform the convolution in frequency domain:

1. Input x1 and store length(x1) in n1.

2. Input x2 and store length(x2) in n2.

3. Create the convolved sequence. i.e. M+N-1 (n1+n2-1) in N and create T=1:N

4. Now calculate the N-point DFT and IDFT as follows:

Take fft(x1,N) and store in y1;

5. Take fft(x2,N) and store in y2;

6. Then multiply the ffts of signals. i.e. y3=y1.*y2. This will give the multiplication.

7. Take the ifft(y3,N).. Your answer should be same as conv(x1,x2)…

CODE:
clear all;
x1=[0 1 2 3]
x2=[2 4 -1 6]
n1=length(x1);
n2=length(x2);
N=n1+n2-1;
T=1:N;
y1=fft(x1,N)
y2=fft(x2,N)
y3=y1.*y2;
subplot 211
plot(y3,T)
title('Convolution in frequency Domain');
subplot 212
z=conv(x1,x2)
plot(z,T)
title('Conv (x1,x2)');
Signals and Systems (EE-311)

Task 3: Find the zeros and poles for the following transfer function using tf2zp and then plot the
pz map to confirm your answer:

CODE:

b=[2 1];
a=[1 3 2];
[b,a]=eqtflength(b,a);
[z,p,k] = tf2zp(b,a)
fvtool(b,a,'polezero')
text(real(z)+.1,imag(z),'Zero')
text(real(p)+.1,imag(p),'Pole')
Signals and Systems (EE-311)
Signals and Systems (EE-311)

Experiment # 09
Implementation and Verification of Periodicity and Harmonics of Periodic
Signals in MATLAB
Objective
The objective of this lab is to understand the periodicity and harmonics of signals.
Apparatus
PC having Matlab.
Theory
A very common class of signals that we encounter is the class of periodic signals. A periodic
continuous time signal has the property that there is a positive value of‘t’ for which
X(t) = x(t + aT) A (continuous time)
Where a = 0, 1,2,3,4 -----------For all values of‘t’.
In other words a periodic signal has the property that it is unchanged by a time shift of ‘T’. In
this case we say that x(t) is periodic signal is the sine signal.
X(t) = sin (wt) , where w = 2πf; therefore X(t) = sin (2πft)
Since sin (Q) = sin(Q + 2π) therefore the signal is periodic with the period ‘2π’.
A periodic signal in discrete time is defined similarly to continuous time periodic signal.
Specifically a discrete time signal x[n] is periodic with period ‘N’ where ‘N’ is positive integer,
i:e if it is unchanged by a time shift of ‘N’ i:e.
X[n] = x[n + bN] (discrete time), where b = 0, 1, 2, 3, 4, -----------
Fundamental period
The fundamental period is the smallest positive value of ‘T’(continuous) or ‘N’ (discrete) for
which the equations of periodicity held. Consider the example of a sine function. In that case the
signal is periodic on 2π, 4π, 6π and so on but the fundamental time period of the signal is 2π.
Example # 1: Matlab explanation of periodic signals.
Code:
t=0:0.01:6;
f=0.5;
x=sin(2*pi*f*t);
plot(t,x);
Its output is shown in Fig. 9.1.
Signals and Systems (EE-311)

Fig. 9.1: Periodic signal


Harmonics
Harmonics are integral multiples of a signal. Consider the signal cos (wot). Its harmonics are
cos(2 wot), cos (3 wot)is the fundamental harmonic.
Even and odd harmonics
If the harmonic of a signal function has an even coefficient it is called an even harmonic.
Otherwise if the coefficient is odd it is called an odd harmonic.
X(t) = Cos (wot)
Cos (2 wot), Cos (4 wot) , Cos (6 wot) …………………….. Even Harmonics
Cos (3 wot), Cos (5 wot) , Cos (7 wot) …………………….. Odd Harmonics
Even, odd harmonic play an important role in signal construction. Different waveforms can be
obtained by adding one type of harmonic e.g adding infinite odd harmonics of sine/cosine where
generates a square wave. Both will have a 90 phase shift from each other. Practically it is not
possible to add all the (infinite) number of harmonics to obtain a perfect square wave but as the
number of harmonics is increased from 10 onwards we obtain a decent square wave.
Example # 2:
Matlab code:
inc = 0.01;
t =0 : inc : 4;
f =0.25;
w = 2 * pi * f ;
fundamental=sin(w*t);
harmaonic2=sin(2*w*t);
harmaonic3=sin(3*w*t);
harmaonic4=sin(4*w*t);
hold on;
plot(t,fundamental,'ro');
plot(t,harmaonic2,'k--');
plot(t,harmaonic3,'m:');
plot(t,harmaonic4,'y');
hold off
Its output is shown in Fig. 9.2.
Signals and Systems (EE-311)

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 0.5 1 1.5 2 2.5 3 3.5 4

Fig. 9.2: Harmonics


Square wave generation by sine functions:
A square wave can be constructed from multiple sine waves at different frequencies as shown in
Fig. 10.3. The sine waves added in addition to the fundamental frequency are called harmonics; a
square wave has harmonics at odd multiples of the fundamental frequency. As higher harmonics
are added, the result gets closer to an ideal square wave, which contains infinite harmonics.

Fig. 9.3: Square wave generation


Code:
A = input('Amplitude = ')
y=0;
for a=1:2:8000
n=0:0.1:15*pi;
x=[A*sin(a*n)/a] ;
y=y+x;
end
plot(n,y,'linewidth',3);
Signals and Systems (EE-311)

xlabel('Time');
ylabel('Amplitude');
title('Square wave Signal');
Its output is shown in Fig. 9.4.
Square wave Signal
20

15

10

5
Amplitude

-5

-10

-15

-20
0 5 10 15 20 25 30 35 40 45 50
Time

Fig. 9.4: Square wave generation by sinewave


Example # 3:
Matlab code:
inc = 0.01;
t =0 : inc : 2;
f =0.5;
w = 2 * pi * f ;
fundamental=cos(w*t);
harmaonic2=cos(2*w*t);
harmaonic3=cos(3*w*t);
harmaonic4=cos(4*w*t);
harmaonic5=cos(5*w*t);
hold on;
plot(t,fundamental,'ro');
plot(t,harmaonic2,'k--');
plot(t,harmaonic3,'m:');
plot(t,harmaonic4,'y');
plot(t,harmaonic5,'b');
hold off
Its output is shown in Fig. 9.5.
1

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2

Fig. 9.5: Graph showing harmonics


Signals and Systems (EE-311)

Comments:-
This lab provides us introduction about the periodicity and harmonics of signals, we learned how
to implement them in MATLAB. We implemented it in lab and observed output.

Conclusion:-
MATLAB is a high-performance language for technical computing. It integrates computation,
programming and visualization in an easy environment where problems and solutions are
expressed in familiar mathematical notations. This lab provides the basic knowledge of plotting
time shifting, scaling and reversal and to implement these signals in MATLAB.
Signals and Systems (EE-311)

Experiment # 11
Implementation and Verification of Sampling Theorem in MATLAB

Objectives
This lab provides an introduction to the concept of sampling and verification of sampling
theorem in MATLAB.
Apparatus
PC having MATLAB
Theory
Period: For periodic waveforms, the duration of the waveform before it repeats is called the
period of the waveform as shown below in Fig. 11.1.

Fig. 11.1: Period of a waveform


Frequency:
Frequency is the rate at which a regular vibration pattern repeats itself (frequency = 1/period).
The unit for frequency is cycles/second, also called Hertz (Hz). The frequency of a waveform
is equal to the reciprocal of the period.
frequency = 1/period
Example:
frequency = 10 Hz
period = .1 (1/10) seconds
frequency = 100 Hz
period = .01 (1/100) seconds
frequency = 261.6 Hz
period = .0038226 (1/ 261.6) seconds
Signals and Systems (EE-311)

Sampling:
To represent waveforms on digital computers, we need to digitize or sample the waveform.
In signal processing sampling is the reduction of a continuous-time signal to a discrete-time
signal. A common example is the conversion of a sound wave (a continuous signal) to a
sequence of samples (a discrete-time signal).A sample is a value or set of values at a point in
time and/or space.
A sampler is a subsystem or operation that extracts samples from a continuous signal. A
theoretical ideal sampler produces samples equivalent to the instantaneous value of the
continuous signal at the desired points. A sample is a value or set of values at a point in time
and/or space. A sampler is a subsystem or operation that extracts samples from a continuous
signal as shown below in Fig. 11.2. A theoretical ideal sampler produces samples equivalent
to the instantaneous value of the continuous signal at the desired points.
Example:

Fig. 11.2: Sampling


Disadvantages of Sampling
 Introduces some noise
 Limits the maximum upper frequency range
Sampling Rate
The sampling rate (SR) is the rate at which amplitude values are digitized from the original
waveform.
CD sampling rate (high-quality):SR = 44,100 samples/second
medium-quality sampling rate:SR = 22,050 samples/second
Phone sampling rate (low-quality):SR = 8,192 samples/second
Higher sampling rates allow the waveform to be more accurately represented. Fig. 11.3
shows different sampling rates.
Signals and Systems (EE-311)

Fig. 11.3: Different sampling rates

Nyquist Theorem and Aliasing


Nyquist Theorem:
Shannon’s theorem tells us that if we have atleast 2 samples per period of a sinusoid, we
have enough information to reconstruct the sinusoid.
Explanation:
According to the Nyquist Theorem, the sampling rate must be at least 2fmax, or twice the
highest analog frequency component. The sampling in an analog-to-digital converter is
actuated by a pulse generator (clock). If the sampling rate is less than 2fmax, some of the
highest frequency components in the analog input signal will not be correctly represented in
the digitized output. When such a digital signal is converted back to analog form by a digital-
to-analog converter, false frequency components appear that were not in the original analog
signal. This undesirable condition is a form of distortion called aliasing.
Aliasing:
One of the limitations of discrete-time sampling is an effect called aliasing. The Nyquist
Theorem states that you need 2 samples per “cycle” of your input signal to define it. Thus,
you can accurately measure the frequency of a signal with frequency f as long as you are
sampling it at greater than 2f. If you try to measure the frequency of signals having a
frequency above f with a sampler operating at 2f, you will alias the signal, or create false
images of this signal at frequencies below f. These false frequencies will appear as mirror
images of the original frequency around the Nyquist frequency. This situation is called
"aliasing back" or "folding back" as described below in Fig 11.4.

Fig. 11.4: Frequency versus amplitude plot showing an aliased signal, fa, which occurs due to
"aliasing back" from the original signal of 70MHz
Signals and Systems (EE-311)

Oversampling
• When we sample at a rate which is greater than the Nyquist rate, we say we are
oversampling as shown below in Fig. 11.5.

Fig. 11.5: Oversampling


Undersampling: When we sample at a rate which is less than the Nyquist rate, we say we are
undersampling and aliasing will yield misleading results as shown in Fig. 11.6.

Fig. 11.6: Undersampling


Code:

function abdulmoeezl15()
f=1000;
T=1/f;
t=0:0.01*T:2*T;
x=cos(2*pi*f*t);
subplot 221
plot(t,x)
title('Continuous Signal')
xlabel('t')
ylabel('x(t)')
fs1=15*f;
n1=0:1/fs1:2*T;
x1=cos(2*pi*f*n1)
subplot 222
stem(n1,x1)
hold on;
Signals and Systems (EE-311)

plot(n1,x1,'k')
hold off;
title('Over Sampling Condition: Fs = 15*F')
xlabel('n')
ylabel('x[n]')
fs2=2*f;
n2=0:1/fs2:2*T;
x2=cos(2*pi*f*n2)
subplot 223
stem(n2,x2)
hold on;
plot(n2,x2,'r')
hold off;
title('Sampling at Nyquist Frequency:Fs = 2F')
xlabel('n')
ylabel('x[n]')
fs3=1.5*f;
n3=0:1/fs3:2*T;
x3=cos(2*pi*f*n3)
subplot 224
stem(n3,x3)
hold on;
plot(n3,x3,'r')
hold off;
title('Under Sampling Condition: Fs=1.5F')
xlabel('n')
ylabel('x[n]')
Its output is shown in Fig. 11.7.
Continuous Signal Over Sampling Condition: Fs = 15*F
1 1
x(n)
x(t)

0 0

-1 -1
0 0.5 1 1.5 2 0 0.5 1 1.5 2
t -3 n -3
x 10 x 10
Sampling at Nyquist Frequency:Fs = 2F Under Sampling Condition: Fs=1.5F
1 1
x(n)

x(n)

0 0

-1 -1
0 0.5 1 1.5 2 0 0.5 1 1.5 2
n -3 n -3
x 10 x 10

Fig. 11.7: Signal and its sampling


Signals and Systems (EE-311)

Output:-

Comments:-
Over-sampling is that when we do sampling greater than normal sampling i.e. >2f and it gives
same signal if we convert back to analogue signal. While under-sampling is that when we did
<2f i.e. less than normal sampling and when we convert back from under-sampling then we get
totally distorted/another signal which is not same as input.

Conclusion:-
This lab provides us introduction about the sampling theorem, under-sampling, over-sampling,
and Nyquist theorem and aliasing. We learned how to implement them in MATLAB. We
implemented it in lab and observed output.
Signals and Systems (EE-311)

Experiment # 12
Implementation of Sound Manipulation and Noise Reduction in MATLAB

Objective:
The objective of this lab is to understand the concept of sound manipulation and how to
reduce noise in sound.
Theory:
Matlab provides functions to read sound files in two formats ‘wavread’ for ‘.wav files’
and ‘auread’ for ‘.au files’. Both return a vector of sound values in the range -1 to 1, the
sampling frequency in Hz, and the number of bits of resolution.
Sound waves are fluctuations in air pressure that have various amplitudes and frequencies.
The amplitude represents the pressure (or intensity) of the sound, while the frequency
specifies how fast the pressure is varying.
MATLAB commands for audio files:
Y= wavread(‘FILE.wav’) reads a WAVE file specified by the string FILE, returning the
sampled data in Y. The ".wav" extension is appended if no extension is given.
[Y,FS,NBITS]= wavread(‘FILE.wav’) returns the sample rate (FS) in Hertz and the number
of bits per sample (NBITS) used to encode the data in the file.
Y=auread(AUFILE) loads a sound file specified by the string AUFILE, returning the
sampled data in y. The ".au" extension is appended if no extension is given.
[Y,Fs,BITS]=auread(AUFILE) returns the sample rate (Fs) in Hertz and the number of bits
per sample (BITS) used to encode the data in the file.
Example:
Command window: >> [Y,FS,NBITS]=wavread('lab.wav')
Output: Its output is shown in Fig. 12.1.

Fig. 12.1: output of wavread( ) command


Signals and Systems (EE-311)

To Read and Play sound in MATLAB:


The command ‘wavplay’ play sound using Windows audio output device. wavplay(Y,FS)
sends the signal in vector Y with sample frequency of FS Hertz to the Windows WAVE
audio device. Standard audio rates are 8000, 11025, 22050, and 44100 Hz. wavplay(Y)
automatically sets the sample rate to 11025 Hz.
Example:
Code:
i=wavread('lab');
wavplay(i,11025)
plot(i)
Output: Its output is shown in Fig. 12.2.

Fig. 12.2: Output of wavplay()


To record sound in MATLAB:
The command ‘wavrecord’ record sound using Windows audio input device.
Example: Recod and play back five seconds of audio sampled at 11.025 kHz.
Code:
Fs=11025
y=wavrecord(5*Fs,Fs)
wavplay(y,Fs)
To reverse the sound in MATLAB:
function abc()
fs=44100
y=wavrecord(10*fs,fs);
wavwrite(y,fs,'lab.wav')
u=wavread('lab.wav')
wavplay(u,fs);
plot(u)
Its output is shown in Fig. 12.3.

Fig. 12.3: Sound Record


Signals and Systems (EE-311)

To write sound file from MATLAB into PC:


The command ‘wavwrite’ write microsoft wave (".wav") sound file. To understand this
consider an example:
function abc()
fs=44100;
y=wavrecord(20*fs,fs);
wavwrite(y,fs,'lab.wav')
x=wavread('lab')
wavplay(x,fs);
subplot (211)
plot(x)
z=flipud(x);
wavplay(z,fs);
subplot(212)
plot(z)
Output: Its output is shown in Fig. 12.4.

Fig. 12.4: Sound recording from Matlab into PC

To add noise to the sound:


Y=awgn(X,SNR) adds white Gaussian noise to X. For this consider an example:
fs=44100;
a=wavread('lab');
n=awgn(a,30);
b=x+n;
wavplay(b,fs)
subplot(311)
plot(a)
subplot(312)
plot(n)
subplot(313)
plot(b)
Output: Its output is shown in Fig. 12.5.
Signals and Systems (EE-311)

Fig. 12.5: Noise Addition into Sound


To add and reduce noise to signal:
To understand the concept that how to add or reduce noise from the signal consider an
example:
function abc ()
f=10;
snr=2
t=0:0.001:1;
fs=1000;
r=fs*t;
x=sin(2*pi*t/fs);
c=awgn(x,snr);
z=abs(fft(x,length(r)));
z1=abs(fft(c,length(r)));
[num,den]= butter(3,2*pi*f/fs);
y=filter(num,den,c);
z2=abs(fft(y,length(r)));
subplot(611)
plot(t,x)
title('info signal')
subplot(612)
plot(r,z)
axis([0 50 0 600]);
title('fft of info signal')
subplot(613)
plot(t,c)
title('noise signal')
subplot(614)
plot(r,z1)
axis([0 50 0 600]);
title('fft of noise signal')
subplot(615)
plot(t,y)
title('filtered signal')
subplot(616)
plot(r,z2)
axis([0 50 0 600]);
title('fft of filtered sigal')

Output: Its output is shown in Fig. 12.6.


Signals and Systems (EE-311)

Fig. 12.6: Addition and reduction of noise

Comments:-
This lab provides us introduction about the sound manipulation and noise reduction, we
learned how to implement them in MATLAB. We implemented it in lab and observed output.

Conclusion:-
MATLAB is a high-performance language for technical computing. It integrates
computation, programming and visualization in an easy environment where problems and
solutions are expressed in familiar mathematical notations. This lab provides the basic
knowledge of plotting time shifting, scaling and reversal and to implement these signals in
MATLAB.
Signals and Systems (EE-311)

Experiment # 13
Verification of Z-Transformation and Related Functions in MATLAB

Objective
This lab provides us introduction about z-transform. We also study about region of convergence
(ROC) and how to implement z-transform and its related functions i.e. ROC in MATLAB.
Apparatus
PC having Matlab
Theory
Z-Transform
In mathematics and signal processing, the Z-transform converts a time domain signal, which is a
sequence of real or complex numbers, into a complex frequency domain representation.

It can be considered as a discrete-time equivalent of the Laplace transform.


Need of Z-transform
Motivation for introducing Z-transformation is that the Fourier transform does not converge for
all systems. So, it is useful to introduce such notation which can be broadens the convergence
scope of signals.
Bilateral Z-transform
The bilateral or two-sided Z-transform of a discrete-time signal x[n] is the formal power series
X(z) defined as:

Where ‘n’ is an integer and ‘z’ is in general, a complex number:

Where A is the magnitude of z, j is the imaginary unit, and ɸ is the complex argument (also
referred to as angle or phase) in radians.
Unilateral Z-transform
Alternatively, in cases where x[n] is defined only for n ≥ 0, the single-sided or unilateral Z-
transform is defined as:
Signals and Systems (EE-311)

In signal processing, this definition can be used to evaluate the Z-transform of the unit impulse
response of a discrete-time causal system.
Matlab implementation: In matlab we use the command of ‘ztrans’ for finding the z-transform
and ‘iztrans’ for finding inverse z-transform of the function or signal. For example:
 Write matlab code for conversion from time domain into frequency domain.
Code:
syms t
x= exp(-2*t)
ztrans(x)
Command window:
x=
1/exp(2*t)
ans =
z/(z - 1/exp(2))

 Conversion from frequency domain into time domain.


Code:
syms z
x=z/(z^2+5*z+6)
iztrans(x)
Command window:
x=
z/(z^2 + 5*z + 6)
ans =
(-2)^n - (-3)^n
Region of convergence (ROC):
The region of convergence (ROC) is the set of points in the complex plane for which the Z-
transform summation converges as shown in Fig. 13.1. We can define it also as the region of
convergence (ROC) is the set of all those values of ‘Z’ for which X(Z) attains a finite value. For
example:
Signals and Systems (EE-311)

Fig. 13.1: Region of convergence


MATLAB can be used to determine the ROC’s of a rational Z-transform.
 The [z, p, k] = tf2zp(num, den) determines the zeros, poles and the gain constant of a
rational Z-transform expressed as a ratio of polynomials in descending powers of z.
 The output files are the column vectors z and p containing the zeros and poles of the
rational Z-transform, and the gain constant k. The statement [num, den ] = tf2zp (z, p, k)
is used in implement the reverse process.
Z-plane:
Z-plane (Z,P) plots the zeros Z and poles P (in column vectors) with the unit circle for reference.
Each zero is represented with a 'o' and each pole with a 'x' on the plot.
Z-plane(B,A) where B and A are row vectors containing transfer function polynomial
coefficients plots the poles and zeros of B(z)/A(z). For example:

Code:
b=[0 1 1/2]
a=[1 3/5 2/25]
zplane(b,a)
Command window:
b=
0 1.0000 0.5000
a=
1.0000 0.6000 0.0800
Its output graph is shown in Fig. 13.2.
Signals and Systems (EE-311)

Fig. 13.2: z-plane


Applications of z-transform:
Z transform is used in many applications of mathematics and signal processing. The lists of
applications of z transform are:
 Uses to analysis of digital filters.
 Used to simulate the continuous systems.
 Analyze the linear discrete system.
 Used to finding frequency response.
 Analysis of discrete signal.
 Helps in system design and analysis and also checks the systems stability.
 For automatic controls in telecommunication.
 Enhance the electrical and mechanical energy to provide dynamic nature of the system.
Lab Tasks
Lab Task 1: Find the z-transforms.
i. t
ii. t2
iii. tn
iv. e-at
v. b= e-at
vi. te-at
vii. 1/a (1-e-at)
viii. (e-at - e-bt)/(b-a)
ix. Sin (wt)
x. Cos (wt)
xi. e-at sin (wt)
xii. e-at Cos (wt)
Lab Task 2: Find the inverse z-transforms of the following.
Signals and Systems (EE-311)

Output:-
Task-1
(i)

(ii)
Signals and Systems (EE-311)

(iii)

(iv)
Signals and Systems (EE-311)

(v)

(vi)
Signals and Systems (EE-311)

(vii)

(viii)
Signals and Systems (EE-311)

(ix)

(x)
Signals and Systems (EE-311)

(xi)

(xii)
Signals and Systems (EE-311)

Task-2
(i)

(ii)
Signals and Systems (EE-311)

Comments:-
In this lab we learned introduction about z-transform and inverse z-transform. We also studied
about region of convergence (ROC) and how to implement z-transform and its related functions
i.e. ROC in MATLAB.
Conclusion:-
MATLAB is a high-performance language for technical computing. It integrates computation,
programming and visualization in an easy environment where problems and solutions are
expressed in familiar mathematical notations. This lab provides the basic knowledge of plotting
time shifting, scaling and reversal and to implement these signals in MATLAB.

You might also like