You are on page 1of 121

LAB MANUAL

SIGNALS AND SYSTEMS

DEPARTMENT OF ELECTRICAL ENGINEERING


NATIONAL UNIVERSITY OF MODERN LANGUAGES | ISLAMABAD
SIGNALS AND SYSTEMS
OBJECTIVES
 The objective of this lab is to develop an understanding of the basic ideas of Signals &
Systems.
 To provide necessary skills to the students for developing professional applications using
state-of-the-art tools and technologies.

INTRODUCTION
This laboratory manual contains exercises based on MATLAB. The purpose of these exercises is
to help re-establish theoretical perspective on signals and systems to practical perspective. The
exercises integrate the basic concepts for both continuous-time and discrete-time signals and
systems. This laboratory manual focuses on an imperative style, where signals and systems are
constructed procedurally.
MATLAB distributed by The Math Works, Inc., is chosen as the basis for these exercises
because it is widely used by practitioners in the field and because it is capable of realizing
interesting systems.
The exercises in this manual cover many of the properties of linear time-invariant (LTI)
systems. It provides an introduction to the basic concepts involved in using MATLAB to
represent signals and systems. Also, the necessary tools for dealing with both numerical and
symbolic expressions are learned. The manual covers a variety of exercises that includes signal
and system representations for both time and frequency domains, basic properties of signals and
systems, the processing of signals by linear systems, Fourier series and transforms, discrete-time
processing of continuous-time signals.

DESIGN SKILLS / TECHNIQUES PRACTICED


The students will practice and implement the following techniques and skills:
1. introduction to the basic concepts involved in using MATLAB.
2. Learn necessary tools for dealing with both numerical and symbolic expressions.
3. Basic concepts involved in using MATLAB to represent signals and systems.
4. Designing professional applications by integrating modern paradigms and
approaches.

SOFTWARE TOOLS / TECHNOLOGY INVOLVEd


Following tools and technologies will be used for implementing software programs in lab:

Department of Electrical Engineering, NUML, Islamabad


SOFTWARE RESOURCES

The lab also consists of the software resources required by the students namely:
1. Pentium-IV PCs (with MS WinXp OS)
2. Matlab 2015

EFFECTIVENESS
After completion of the lab, the students will acquire the required skills and knowledge to
develop applications related to signals and systems. They will be able to analyze a given problem
and select suitable controls and operations for its implementation on Matlab. The students will be
able to develop applications that integrate real-time problems and applications.
With the help of the threads of the lab mentioned above, students will have a clear understanding
of all the three paradigms of implementation of digital logic circuits: • Learn necessary tools for
dealing with both numerical and symbolic expressions • Basic concepts involved in using
MATLAB • Basic concepts involved in using MATLAB to represent signals and systems. This
makes students adept in basic concepts involved in signals and sytems. The lab contributes a lot
to the basic learning of signals. This shows the indispensability of the signals and systems Lab.
The lab exercises introduced the fundamental ideas of signal and system analysis that will help
the students to understand the engineering systems in many diverse areas, including seismic data
processing, communications, speech processing, image processing, and defense electronics.

Department of Electrical Engineering, NUML, Islamabad


SIGNALS AND SYSTEMS
DEPARTMENT OF ELECTRICAL ENGINEERING
NATIONAL UNIVERSITY OF MODERN LANGUAGES ISLAMABAD

LAB OUTLINE
Week No. Signals and Systems Lab
Introduction to MATLAB and basic commands.

1  Introduction to Matlab, Arithmetic, trigonometric and logical


operations.
 Graphical representation and plotting of signals.

Scripts, Functions, Flow Control, and Symbolic Math’s Toolbox using


MATLAB.
2
 Generation of M-file and flow control operations.
 Funtions and analytical math operations
Study Signals & their Classifications using MATLAB.
3
 Signal generation in Matlab.
 Classification of signals in Matlab.
Study Operations on the signals using MATLAB.
4
 Signals classified based on domain and its implementation in Matlab.
 Signals classified based on range and its implementation in Matlab.
Study Basic Signals using MATLAB.
5  Different type of signals in matlab.
 Generation of basic sequences and signals and their use in generating
other sequences.
Study Convolution and properties of Linear time-invariant system
using MATLAB.
6
 basic concept of system characteristics.
 Properties of LTI system.

Periodicity, harmonics and Fourier series using MATLAB.


7  Definition of periodicity and harmonics.
 Implement fourier series using Matlab on basic signals.

8 Study Fourier transform using MATLAB.

Department of Electrical Engineering, NUML, Islamabad


 Fourier transform using Matlab.
 Inverse Fourier transform using Matlab.
Open Ended Lab
9
 Study and implement the designated task using Matlab.
Study Sound Manipulation and Play Back using MATLAB
10  Load sound and audio file in matlab.
 Simple operations i.e. delay, echo etc on audio file using Matlab.
Study Laplace Transforms using MATLAB.
11  Laplace transform using Matlab.
 Laplace transform using Matlab.

Implementation of GUI in MATLAB.


 Basics of GUI in Matlab.
12  Design and configuration of different buttons and operations in GUI.
 Plotting of graphs in GUI.

Exploration of Simulink Library in MATLAB.

13  Basics of Simulink in Matlab.


 Configuration and use of different blocks and operations in simulink.
 Plotting of graphs in simulink.
Study and Implementation of spectral analysis in MATLAB
14  Different frequency analysis using Matlab.

Department of Electrical Engineering, NUML, Islamabad


Contents
LAB 1: INTRODUCTION TO MATLAB AND BASIC FUNCTIONS.............................................................9
OBJECTIVE:-................................................................................................................................................................9
EQUIPMENT REQUIRED:-...........................................................................................................................................9
THEORY................................................................................................................................................................... 9
ANALYSIS.............................................................................................................................................................. 20
LAB ASSIGNMENT..................................................................................................................................................20
CONCLUSION..........................................................................................................................................................20
LAB 2: SCRIPTS, FUNCTIONS, FLOW CONTROL AND SYMBOLIC MATH’S TOOLBOX...................21
OBJECTIVE............................................................................................................................................................. 21
EQUIPMENT REQUIRED...........................................................................................................................................21
THEORY................................................................................................................................................................. 21
ANALYSIS.............................................................................................................................................................. 30
LAB ASSIGNMENT..................................................................................................................................................30
CONCLUSION..........................................................................................................................................................30
LAB 3: SIGNALS AND THEIR CLASSIFICATION......................................................................................31
OBJECTIVE:-...........................................................................................................................................................31
EQUIPMENT REQUIRED:-.........................................................................................................................................31
THEORY................................................................................................................................................................. 31
ANALYSIS.............................................................................................................................................................. 40
LAB ASSIGNMENT..................................................................................................................................................40
CONCLUSION..........................................................................................................................................................40
LAB 4: OPERATIONS ON SIGNALS USING MATLAB..............................................................................41
OBJECTIVE:-...........................................................................................................................................................41
EQUIPMENT REQUIRED:-.........................................................................................................................................41
THEORY:..............................................................................................................................................................41
ANALYSIS.............................................................................................................................................................. 50
LAB ASSIGNMENT..................................................................................................................................................50
CONCLUSION..........................................................................................................................................................50
LAB 5: STUDY BASIC SIGNALS USING MATLAB.....................................................................................51
OBJECTIVE:-...........................................................................................................................................................51
EQUIPMENT REQUIRED:-.........................................................................................................................................51
THEORY:..............................................................................................................................................................51
ANALYSIS.............................................................................................................................................................. 57
LAB ASSIGNMENT..................................................................................................................................................57
CONCLUSION..........................................................................................................................................................57
LAB 6: STUDY CONVOLUTION & PROPERTIES OF LTI SYSTEM USING MATLAB...........................58
OBJECTIVE:-...........................................................................................................................................................58
EQUIPMENT REQUIRED:-.........................................................................................................................................58
THEORY:..............................................................................................................................................................58
ANALYSIS.............................................................................................................................................................. 65
LAB ASSIGNMENT..................................................................................................................................................65
CONCLUSION.............................................................................................................................................................65
LAB 7: PERIODICITY, HARMONICS AND FOURIER SERIES USING MATLAB...................................66
OBJECTIVE:-...........................................................................................................................................................66
EQUIPMENT REQUIRED:-.........................................................................................................................................66
THEORY:..............................................................................................................................................................66
ANALYSIS.............................................................................................................................................................. 72
LAB ASSIGNMENT..................................................................................................................................................72
CONCLUSION..........................................................................................................................................................72
LAB 8: STUDY FOURIER TRANSFORM USING MATLAB.......................................................................73
OBJECTIVE:-...........................................................................................................................................................73
EQUIPMENT REQUIRED:-.........................................................................................................................................73
THEORY:..............................................................................................................................................................73
ANALYSIS.............................................................................................................................................................. 78
LAB ASSIGNMENT..................................................................................................................................................78
CONCLUSION..........................................................................................................................................................78
LAB 9: OPEN ENDED LAB............................................................................................................................ 79
OBJECTIVE:-...........................................................................................................................................................79
EQUIPMENT REQUIRED:-.........................................................................................................................................79
LAB 10: STUDY SOUND MANIPULATION AND PLAYBACK USING MATLAB.....................................81
OBJECTIVE:-...........................................................................................................................................................81
EQUIPMENT REQUIRED:-.........................................................................................................................................81
THEORY:..............................................................................................................................................................81
ANALYSIS.............................................................................................................................................................. 87
LAB ASSIGNMENT..................................................................................................................................................87
CONCLUSION..........................................................................................................................................................87
LAB 11: STUDY LAPLACE TRANSFORM USING MATLAB.....................................................................88
OBJECTIVE:-...........................................................................................................................................................88
EQUIPMENT REQUIRED:-.........................................................................................................................................88
THEORY:..............................................................................................................................................................88
ANALYSIS.............................................................................................................................................................. 92
LAB ASSIGNMENT..................................................................................................................................................92
CONCLUSION..........................................................................................................................................................92
LAB 12: IMPLEMENTATION OF GUI IN MATLAB...................................................................................93
OBJECTIVE:-...........................................................................................................................................................93
EQUIPMENT REQUIRED:-.........................................................................................................................................93
THEORY:..............................................................................................................................................................93
ANALYSIS............................................................................................................................................................ 102
LAB ASSIGNMENT................................................................................................................................................102
CONCLUSION........................................................................................................................................................102
LAB 13: EXPLORATION OF SIMULINK LIBRARY IN MATLAB...........................................................103
OBJECTIVE:-.........................................................................................................................................................103
EQUIPMENT REQUIRED:-.......................................................................................................................................103

Department of Electrical Engineering, NUML, Islamabad


THEORY:...............................................................................................................................................................103
ANALYSIS................................................................................................................................................................ 4
LAB ASSIGNMENT....................................................................................................................................................4
CONCLUSION............................................................................................................................................................4
LAB 14: STUDY AND IMPLEMENTATION OF SPECTRAL ANALYSIS IN MATLAB..............................5
OBJECTIVE:-.............................................................................................................................................................5
EQUIPMENT REQUIRED:-...........................................................................................................................................5
THEORY:................................................................................................................................................................5
ANALYSIS................................................................................................................................................................ 7
LAB ASSIGNMENT....................................................................................................................................................7
CONCLUSION............................................................................................................................................................7

Department of Electrical Engineering, NUML, Islamabad


LAB 1: Introduction to Matlab and basic functions
Objective:-

 Basics of Matlab.
 To study arithmetic and logical operations using matlab i.e. Creating Matrices, Adding and
Subtracting Matrices, Vector Products and Transpose, Multiplying Matrices, The Identity Matrix,
Solving Linear Systems of Equations.

Equipment required:-
o Computer work station
o Matlab 2015

Theory

Overview of MATLAB Data Types

There are 15 fundamental data types in MATLAB. Each of these data types is in the form of a
matrix or array. This matrix or array is a minimum of 0-by-0 in size and can grow to an n-
dimensional array of any size.

All of the fundamental data types are shown in lowercase text in the diagram below. Additional
data types are user-defined, object-oriented user classes and Java classes. You can use the latter
with the MATLAB interface to Java.

You can create two-dimensional double and logical matrices using one of two storage formats:
full or sparse. For matrices with mostly zero-valued elements, a sparse matrix requires a fraction
of the storage space required for an equivalent full matrix. Sparse matrices invoke methods
especially tailored to solve sparse problems.

Department of Electrical Engineering, NUML, Islamabad


The following table describes these data types in more detail.

Data Type Example Description

int8, uint8, uint16(65000) Array of signed and unsigned integers. Requires less storage
int16, space than single or double. All integer types except for int64
uint16, and uint64 can be used in mathematical operations.
int32,
uint32,
int64,
uint64

single 3 * 10^38 Array of single-precision numbers. Requires less storage space


than double, but has less precision and a smaller range.

double 3 * 10^300 Array of double-precision numbers. Two- dimensional arrays


5 + 6i can be sparse. The default numeric type in MATLAB.

logical magic(4) > 10 Array of logical values of 1 or 0 to represent true and false
respectively. Two-dimensional arrays can be sparse.

char 'Hello' Array of characters. Strings are represented as vectors of


characters. For arrays containing more than one string, it is best
to use cell arrays.

cell array a{1,1} = 12; Array of indexed cells, each capable of storing an array of a
a{1,2} = 'Red'; different dimension and data type.
a{1,3} =
magic(4);

structure a.day = 12; Array of C-like structures, each structure having named fields
a.color = 'Red'; capable of storing an array of a different dimension and data
a.mat = magic(3); type.

function @sin Pointer to a function. You can pass function handles to other
handle functions.

user class polynom([0 -2 - Objects constructed from a user-defined class.


5])

Java class java.awt.Frame Objects constructed from a Java class.

Department of Electrical Engineering, NUML, Islamabad


Complex Numbers, Infinity and NaN, Working with M-Files, MATLAB Plotting Tools, 3-D
Visualization
STARTING MATLAB:
To start MATLAB from Windows, double-click the MATLAB icon on your Windows desktop.
When MATLAB starts, the MATLAB desktop opens as shown in Figure 1.1. The window in the
desktop that concerns us for this chapter is the Command Window, where the special _ prompt
appears.
This prompt means that MATLAB is waiting for a command. You can quit MATLAB at any time
with one of the following:
• Select Exit MATLAB from the desktop File menu.
• Enter quit or exit at the Command Window prompt.

BEGINNING WORK ON MATLAB


Once MATLAB has been successfully started, start the following set of activities to begin
working on MATLAB.
1. Basic Arithmetic Operations

(a) Type 2+3 after the >> prompt, followed by Enter, i.e. press the Enter key, as indicated by
<Enter>, below:
>> 2+3 <Enter>
Commands are only carried out when you press Enter. The answer in this case is, of course, 5.
(b) Next try the following:

Department of Electrical Engineering, NUML, Islamabad


>> 3-2 <Enter>
>> 2*3 <Enter>
>> 1/2 <Enter>
>> 2ˆ3 <Enter>
>> 2\1 <Enter>
What about (1)/(2) and (2)ˆ(3)? Can you figure out what the symbols *, / and ˆ mean?
Yes, they are multiplication, division and exponentiation. The backslash means the denominator is
to the left of the symbol and the numerator is to the right of the symbol; the result for the last
command is 0.5. This operation is equivalent to 1/2.
(c) How do you think MATLAB would handle 0/1 and 1/0? Try it. MATLAB is sensible about
anticipating some errors; it warns you in case you didn’t realize you were dividing by zero, but
still gives the answer Inf. If you insist on using ∞ in a calculation, which you may legitimately
wish to do, type the symbol Inf (short for infinity), e.g. try 13+Inf and 29/Inf.
(d) Another special value that you may meet is NaN, which stands for Not-a-Number. It is the
answer to calculations like 0/0.
2. Assigning Values to Variables
(a) Enter the command (in programming jargon a statement)a = 2, i.e. the MATLAB command
line should look like this:

>> a = 2 <Enter>
The symbol ‘a’ is called a variable. This statement assigns the value of 2 to a. (Note that this
value is displayed immediately after the statement is executed.) Now try entering the statement
>> a = a + 7
followed on a new line by a = a * 10. Do you agree with the final value of a? Do we agree that it is
90?
(b) Now enter the statement
>> b = 3; <Enter>
The semicolon (;) prevents the value of b from being displayed. However, b still has the value 3 as
you can see by entering its name without a semicolon, i.e. by executing the following command:
>> b <Enter>.
(c) Assign any values you like to two variables x and y. Now see if you can in a single statement
assign the sum of x and y to a third variable z. One way of doing this is
>> x = 2; y = 3; <Enter>
>> z = x + y <Enter>

Department of Electrical Engineering, NUML, Islamabad


Notice that, in addition to doing the arithmetic with variables with assigned values, several
commands separated by semicolons (or by commas) can be put on one line.
3. Basic Scientific Functions (sin, cos, log, etc)

MATLAB has all of the usual mathematical functions that are on a scientific-electronic
calculator, like sin, cos, log (meaning the natural logarithm), as well as a lot more.
(a) Find √π with the command sqrt(pi). The answer should be 1.7725. Note that MATLAB knows
the value of pi, because it is one of MATLAB’s many built-in functions.
(b) Trigonometric functions like sin(x) expect the argument x to be in radians. Multiply
degrees by π/180 to get radians. For example, use MATLAB to calculate sin (90°). The answer
should be 1, i.e. sin(90*pi/180).
(c) The exponential function ex is computed in MATLAB as exp(x). Use this information to find
eand 1/e (2.7183 and 0.3679). Note that, because of the numerous built-in functions like pi or sin,
care must be exercised in the naming of user-defined variables. The name of user-defined
variables should not duplicate the name of a built-in function unless it is deliberately done for a
good reason. This problem can be illustrated as follows. Try the following:
>> pi = 4 <Enter>
>> sqrt(pi) <Enter>
>> whos <Enter>
>> clear pi <Enter>
>> whos <Enter>
>> sqrt(pi) <Enter>
>> clear <Enter>
>> whos <Enter>
Note that clear executed by itself clears all of the local variables in the workspace. Executing the
command clear pi clears the locally defined variable pi. Hence, if you decided to redefine a built-
in function or command, the newly defined value is used! The command whos is executed to
determine the list of local variables or commands presently in the workspace. The first execution
of the command pi = 4 in the above example displays your redefinition of the built-in number pi.
It is a 1-by-1 (or 1x1) double array, which means this data type was created when pi was assigned
a number (you will learn more about other data types later, as we proceed in our investigation of
MATLAB).
The command “clear” removes all user-defined variables from memory. Use it frequently to
remove all previously defined variables, and especially at the beginning of each program.
Otherwise, it is possible that your program/commands may be using the older values of the
variable, which you do not want.
Department of Electrical Engineering, NUML, Islamabad
4. General Functions in MATLAB
MATLAB has numerous general functions. For example, try date and calendar for starters. More
can be discovered by going to the Help menu in MATLAB.
5. General Commands and Operators in MATLAB
MATLAB also has numerous commands, such as clc (for clear command window). Help is
another command you will use a lot (see below). The difference between functions and commands
is that functions usually return with a value, e.g. the date, while commands tend to change the
environment in some way, e.g. by clearing the screen, or saving some statements to the workspace
(on the disk).
>> clc <Enter>
>> help [name of any command] <Enter>
>> help date <Enter>

Operators

Expressions use familiar arithmetic operators and precedence rules.

+    Addition

- Subtraction

* Multiplication

/ Division

\ Left division (described in "Matrices and Linear Algebra" in the MATLAB documentation)

^ Power

' Complex conjugate transpose

() Specify evaluation order

Functions

MATLAB provides a large number of standard elementary mathematical functions, including abs,
sqrt, exp, and sin. Taking the square root or logarithm of a negative number is not an error; the
appropriate complex result is produced automatically. MATLAB also provides many more
advanced mathematical functions, including Bessel and gamma functions. Most of these functions
accept complex arguments. For a list of the elementary mathematical functions, type

 help elfun
Department of Electrical Engineering, NUML, Islamabad
For a list of more advanced mathematical and matrix functions, type

 help specfun
 help elmat

Some of the functions, like sqrt and sin, are built in. Built-in functions are part of the MATLAB
core so they are very efficient, but the computational details are not readily accessible. Other
functions, like gamma and sinh, are implemented in M-files.

There are some differences between built-in functions and other functions. For example, for built-
in functions, you cannot see the code. For other functions, you can see the code and even modify
it if you want.

Several special functions provide values of useful constants.

pi 3.14159265...

i
Imaginary unit,

j Same as i

eps
Floating-point relative precision,

realmin   
Smallest floating-point number,

realmax
Largest floating-point number,

Inf Infinity

NaN Not-a-number

Infinity is generated by dividing a nonzero value by zero, or by evaluating well defined


mathematical expressions that overflow, i.e., exceed realmax. Not-a-number is generated by trying
to evaluate expressions like 0/0 or Inf-Inf that do not have well defined mathematical values.

Department of Electrical Engineering, NUML, Islamabad


The function names are not reserved. It is possible to overwrite any of them with a new variable,
such as

 eps = 1.e-6

and then use that value in subsequent calculations. The original function can be restored with

 clear eps

Examples of Expressions

You have already seen several examples of MATLAB expressions. Here are a few more
examples, and the resulting values.

rho = (1+sqrt(5))/2
rho =
1.6180

a = abs(3+4i)
a=
5

z = sqrt(besselk(4/3,rho-i))
z=
0.3730+ 0.3214i

huge = exp(log(realmax))
huge =
1.7977e+308

toobig = pi*huge
toobig =
Inf

ELEMENTARY MATH FUNCTIONS


1. Trigonometric

 sin - Sine.
 sinh - Hyperbolic sine.
 asin - Inverse sine.
 asinh - Inverse hyperbolic sine.
 cos - Cosine.
 cosh - Hyperbolic cosine.
 acos - Inverse cosine.
 acosh - Inverse hyperbolic cosine.
 tan - Tangent.
 tanh - Hyperbolic tangent.
Department of Electrical Engineering, NUML, Islamabad
 atan - Inverse tangent.
 atan2 - Four quadrant inverse tangent.
 atanh - Inverse hyperbolic tangent.
 sec - Secant.
 sech - Hyperbolic secant.
 asec - Inverse secant.
 asech - Inverse hyperbolic secant.
 csc - Cosecant.
 csch - Hyperbolic cosecant.
 acsc - Inverse cosecant.
 acsch - Inverse hyperbolic cosecant.
 cot - Cotangent.
 coth - Hyperbolic cotangent.
 acot - Inverse cotangent.
 acoth - Inverse hyperbolic cotangent.

2. Exponential.
 exp - Exponential.
 log - Natural logarithm.
 log10 - Common logarithm.
 sqrt - Square root.

3. Complex.
 abs - Absolute value.
 angle - Phase angle.
 conj - Complex conjugate.
 imag - Complex imaginary part.
 real - Complex real part.

4. Numeric.
 fix - Round towards zero.
 floor - Round towards minus infinity.
 ceil - Round towards plus infinity.
 round - Round towards nearest integer.
 rem - Remainder after division.
 sign - Signum function.

5. Arithmetic operators.
Department of Electrical Engineering, NUML, Islamabad
 + Plus
 - Minus
 * Matrix multiplication
 .* Array multiplication
 ^ Matrix power
 .^ Array power
 \ Backslash or left division
 / Slash or right division
 ./ Array division

6. Relational operators.
 == Equality
 <,> Relational operators
 & Logical AND
 | Logical OR
 ~ Logical NOT
 xor Logical EXCLUSIVE OR
 ~= Not equal
 < Less than (lt)
 > Greated than (gt)
 <= Less than or equal to (le)
 >= Greater than or equal to (ge)

MATRICES IN MATLAB

This section introduces you to other ways of creating matrices:

Generating Matrices
The load Function
M-Files
Concatenation
Deleting Rows and Columns

Generating Matrices

MATLAB provides four functions that generate basic matrices. These are listed below:

zeros All zeros

ones All ones

rand Uniformly distributed random elements

randn      Normally distributed random elements

Department of Electrical Engineering, NUML, Islamabad


Here are some examples.

Z = zeros(2,4)
Z=
0 0 0 0
0 0 0 0

F = 5*ones(3,3)
F=
5 5 5
5 5 5
5 5 5

N = fix(10*rand(1,10))
N=
     9 2 6 4 8 7 4 0 8 4

R = randn(4,4)
R=
    0.6353 0.0860 -0.3210 -1.2316
-0.6014 -2.0046 1.2366 1.0556
0.5512 -0.4931 -0.6313 -0.1132
-1.0998 0.4620 -2.3252 0.3792

Questions

Below are given three exercises. Solve and verify the answers.

1. Given x = -5 + 9i and y = 6 – 2i, use MATLAB to show that x + y = 1 + 7i, xy


= -12 + 64i, and x / y = -1.2 + 1.1i.
2. Given x = 3+2i, y = 9+7i and z = 4+6i, compute x*y*z, (x*y)/z and (x+y)/(z+x).
3. Use MATLAB to compute: 6(351/4) + 140..35
ANS : >> 6 * (35 ^ (1/4)) + 14 ^ 0.35 <Enter> 17.1123

Department of Electrical Engineering, NUML, Islamabad


Analysis
LAB Task (Lab # 1)
1.) Set x = 4+Roll Number, y = 12+ Roll Number, z = -2+ Roll Number and find the
following
(a) y/x*z
(b) y/(x*z)
Are these different? Why or why not?
2.) Find the square root of x, y, and z above using the built in matlab function.
3.) Evaluate the following using matlab:
sin( /3), cos( / 4), tan( / 2), arcsin(0), |z| , ln(x), e y
Anything interesting happens?
4.) Create the following row vector a [1,2+Roll Number,3,4+Roll
number,5,6+Roll number] two different ways.
5.) Make a column vector b that is the transpose of a two different ways.
6.) Create a vector c that is the same as a but whose second component is the last
component
of b.
7.) Create a 4x4 array

[ ]
2 7 5+ Roll number 1
−3 5 7+ Roll number 8
A= −1 6 0+ Roll number 9
−1 4 3+ Roll number 2

8.) What is A’?


9.) Set a column vector d equal to the first row of A using ‘:’ notation and set a
vector e
equal to the first row of A using the column notation.
−π π
10.) Create a vector, u, of 15 equally spaced points between 2 and 2 .
Note:
Plagiarized data will get zero marks.

Lab Assignment
Make a neat Lab report.

Conclusion
In this Lab we study the implementation and use of basic operations in Matlab.

Department of Electrical Engineering, NUML, Islamabad


LAB 2: Scripts, Functions, Flow Control and Symbolic Math’s
Toolbox
Objective
The objective of this lab is to introduce you to writing M-file scripts, creating MATLAB
Functions and reviewing MATLAB flow control commands.
Equipment Required
• A Computer
• Matlab 2015
Theory
MATLAB is a powerful programming language as well as an interactive computational
environment. Files that contain code in the MATLAB language are called M-files. You create
M-files using a text editor, then use them as you would any other MATLAB function or
command. There are two kinds of M-files:
 Scripts, which do not accept input arguments or return output arguments. They
operate on data in the workspace. MATLAB provides a full programming language
that enables you to write a series of MATLAB statements into a file and then execute
them with a single command. You write your program in an ordinary text file, giving
the file a name of ‘filename.m’. The term you use for ‘filename’ becomes the new
command that MATLAB associates with the program. The file extension of .m makes
this a MATLAB M-file.
 Functions, which can accept input arguments and return output arguments. Internal
variables are local to the function.
If you're a new MATLAB programmer, just create the M-files that you want to try out in the
current directory. As you develop more of your own M-files, you will want to organize them
into other directories and personal toolboxes that you can add to your MATLAB search path. If
you duplicate function names, MATLAB executes the one that occurs first in the search path.
a. Scripts
When you invoke a script, MATLAB simply executes the commands found in the file. Scripts
can operate on existing data in the workspace, or they can create new data on which to operate.
Although scripts do not return output arguments, any variables that they create remain in the
workspace, to be used in subsequent computations. In addition, scripts can produce graphical
output using functions like plot. For example, create a file called ‘myprogram.m’ that contains
these MATLAB commands:

% Create random numbers and plot these numbers clc


clear
r = rand(1,50)
plot(r)

Typing the statement ‘myprogram’ at command prompt causes MATLAB to execute the
commands, creating fifty random numbers and plots the result in a new window. After
execution of the file is complete, the variable ‘r’ remains in the workspace.

Department of Electrical Engineering, NUML, Islamabad


b. Functions
Functions are M-files that can accept input arguments and return output arguments. The names
of the M-file and of the function should be the same. Functions operate on variables within their
own workspace, separate from the workspace you access at the MATLAB command prompt.
An example is provided below:

function ave = average(x)


ave = sum(x(:))/numel(x);
end

Command-Window
>> x=[1 2 3 4 5 6];
>> ave=average(x)
ave =
3.5000
c. Flow Control

Conditional Control – if, else, switch


This section covers those MATLAB functions that provide conditional program control.
if, else, and elseif. The if statement evaluates a logical expression and executes a group of
statements when the expression is true. The optional elseif and else keywords provide for the
execution of alternate groups of statements. An end keyword, which matches the if, terminates
the last group of statements.
The groups of statements are delineated by the four keywords—no braces or brackets are involved
as given below
if <condition>
<statements>;

elseif <condition>
<statements>;

Else
<statements>;
end
It is important to understand how relational operators and if statements work with matrices.
When you want to check for equality between two variables, you might
use if A == B, ...
This is valid MATLAB code, and does what you expect when A and B are scalars. But when
A and B are matrices, A == B does not test if they are equal, it tests where they are equal; the
result is another matrix of 0's and 1's showing element-by-element equality. (In fact, if A and
B are not the same size, then A == B is an error.)

Department of Electrical Engineering, NUML, Islamabad


>>A = magic(4);
>>B = A;
>>B(1,1) = 0;
>>A == B
ans =
0 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
The proper way to check for equality between two variables is to use the isequal function:

if isequal(A, B), ...

isequal returns a scalar logical value of 1 (representing true) or 0 (false), instead of a matrix,
as the expression to be evaluated by the if function.
Using the A and B matrices from above, you get

>>isequal(A, B)
ans =
0

Here is another example to emphasize this point. If A and B are scalars, the following program
will never reach the "unexpected situation". But for most pairs of matrices, including our
magic squares with interchanged columns, none of the matrix conditions A > B, A < B, or A
== B is true for all elements and so the else clause is executed:
if A > B

'greater
' elseif A < B

'less'
elseif A == B

'equal'
else

error('Unexpected situation')

end

Several functions are helpful for reducing the results of matrix comparisons to scalar
conditions for use with if, including ‘isequal’, ‘isempty’, ‘all’, ‘any’.
d. Switch and Case:
The switch statement executes groups of statements based on the value of a variable or
expression. The keywords case and otherwise delineate the groups. Only the first matching
case is executed. The syntax is as follows:

switch <condition or expression>


case <condition>

Department of Electrical Engineering, NUML, Islamabad


<statements>;

case <condition>

otherwise
<statements>;
end

switch rem(n,2) % to find remainder of any number


‘n’ case 0
disp(‘Even Number’) % if remainder is
zero case 1
disp(‘Odd Number’) % if remainder is one
end
Note: Unlike the C language switch statement, MATLAB switch does not fall through. If the
first case statement is true, the other case statements do not execute. So, break statements are
not required.
e. For, while, break and continue:
This section covers those MATLAB functions that provide control over program loops.

a) for:
The ‘for’ loop, is used to repeat a group of statements for a fixed, predetermined
number of times. A matching ‘end’ delineates the statements. The syntax is as follows:

for <index> = <starting number>:<step or increment>:<ending number>


<statements>;
end

for n = 1:4
r(n) = n*n; % square of a number
end
r

The semicolon terminating the inner statement suppresses repeated printing, and the r after the
loop displays the final result.

It is a good idea to indent the loops for readability, especially when they are nested:

for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end

end

b) while:
The ‘while’ loop, repeats a group of statements indefinite number of times under control of a
Department of Electrical Engineering, NUML, Islamabad
logical condition. So a while loop executes atleast once before it checks the condition to stop
the execution of statements. A matching ‘end’ delineates the statements. The syntax of the
‘while’ loop is as follows:
while <condition>
<statements>;
end

Here is a complete program, illustrating while, if, else, and end, that uses interval bisection to
find a zero of a polynomial:

j=1;
while (j<=4 )
a(j)=10*j;
j=j+1;
end
a

The result is a matrix ‘a’ whose values are [10 20 30 40]. The cautions involving matrix
comparisons that are discussed in the section on the ‘if’ statement also apply to the while
statement.

c) break:
The break statement lets you exit early from a ‘for’ loop or ‘while’ loop. In nested loops,
break exits from the innermost loop only.

a=0; b=0;
for i=1:10,
if(i==6)
break
; end
a(i)=i;
end
a

d) continue:
The continue statement passes control to the next iteration of the for loop or while loop in
which it appears, skipping any remaining statements in the body of the loop. The same holds
true for continue statements in nested loops. That is, execution continues at the beginning of
the loop in which, the continue statement was encountered.

for j=1:10,
if(j==6)
continue;
end
b(j)=j
;
Department of Electrical Engineering, NUML, Islamabad
end
b
f. Symbolic Math’s Toolbox:
a. Overview:
Symbolic Math Toolbox™ and Extended Symbolic Math Toolbox™ software incorporates
symbolic computation into the numeric environment of MATLAB® software. These
toolboxes supplement MATLAB numeric and graphical capabilities with several other types
of mathematical computation.
b. Symbolic Object:
Symbolic Math Toolbox™ software defines a new MATLAB® data type called a symbolic
object. Internally, a symbolic object is a data structure that stores a string representation of
the symbol. Symbolic Math Toolbox software uses symbolic objects to represent symbolic
variables, expressions, and matrices.

The following example illustrates the difference between a standard MATLAB data type,
such as double, and the corresponding symbolic object. The MATLAB command

sqrt(2)
returns a floating-point decimal number:

ans =
1.4142

On the other hand, if you convert 2 to a symbolic object using the sym command, and then
take its square root by entering:

a = sqrt(sym(2))
the result is

a =2^(1/2)

MATLAB gives the result 2^(1/2) using symbolic notation for the square root operation,
without actually calculating a numerical value. MATLAB records this symbolic expression in
the string that represents 2^(1/2). You can always obtain the numerical value of a symbolic
object with the double command:

double(a)
ans =
1.4142

Notice that the result is indented, which tells you it has data type double. Symbolic results
are not indented.

If you set a variable equal to a symbolic expression, and then apply the syms command to the
variable, MATLAB® software removes the previously defined expression from the variable.
For example,

syms a b
Department of Electrical Engineering, NUML, Islamabad
f=a+b

returns

f = a+b
c. Substitution:
You can substitute a numerical value for a symbolic variable using the subs command. For
example, to substitute the value x = 2 in the symbolic expression,
syms x
syms x
f = 2*x^2 - 3*x + 1
enter the command:
subs(f,2)

This returns f (2):


ans = 3

When your expression contains more than one variable, you can specify the variable for
which you want to make the substitution. For example, to substitute the value x = 3 in the
symbolic expression,
syms x y
f = x^2*y + 5*x*sqrt(y)
enter the command:
subs(f, x, 3) This returns ans = 9*y+15*y^(1/2)

On the other hand, to substitute y = 3, enter


subs(f, y, 3) ans =
3*x^2+5*x*3^(1/2)

If you want to substitute x=2, and y=3, enter


subs(f,{x,y},{2,3}) ans =
29.3205
d. Differentiation:
To illustrate how to take derivatives using Symbolic Math Toolbox™ software, first create a
symbolic expression:

syms x
f = sin(5*x)

The command diff(f) differentiates f with respect to x:


ans = 5*cos(5*x)
As another example, let g = exp(x)*cos(x)

where exp(x) denotes ex, and to differentiate g:

diff(g)
ans =
exp(x)*cos(x)-exp(x)*sin(x)
Department of Electrical Engineering, NUML, Islamabad
To take the second derivative of g, enter
diff(g,2)
ans =
-2*exp(x)*sin(x)
You can get the same result by taking the derivative twice:
diff(diff(g)) ans =
-2*exp(x)*sin(x)

In this example, MATLAB® software automatically simplifies the answer. However, in


some cases, MATLAB might not simply an answer, in which case you can use the simplify
command. Note that to take the derivative of a constant, you must first define the constant as
a symbolic expression. For example, entering
c = sym('5'); diff(c) returns
ans = 0

If you just enter


diff(5)

MATLAB returns
ans =
[]
because 5 is not a symbolic expression.

syms h n x
limit( (cos(x+h) - cos(x))/h,h,0 )

which return
ans =
-sin(x)

Department of Electrical Engineering, NUML, Islamabad


Another Example:

limit( (1 + x/n)^n,n,inf )

Analysis
LAB Task (Lab # 2)
1. MATLAB M-file Script
Use MATLAB to generate the first 100 terms in the sequence a (n) define recursively by
a(n+1)=p*a(n)*(1-a(n)) with p=2.9 and a(1) = 0.5.
2. MATLAB M-file Function
Use ‘for’ or ‘while’ loop to convert degrees Fahrenheit (Tf) to degrees Celsius using the
9
following equation.T f = ∗T c +32 Use any starting temperature, increment and
5
ending temperature (example: starting temperature=0, increment=10+roll number, ending
temperature= 200+roll number).
3. MATLAB Plotting
Plot the function
Y(x) = exp (-x) sin ((8+roll number)*x) for 0 ≤x ≤ 2π.
4. MATLAB Flow Control
Write your own MATLAB functions to compute the exponential function using the
Taylor series expansion, use for loop then while loop:

e x = 1 + x + x 2/2! + x 3/3!+… …… + x RN /10!

Department of Electrical Engineering, NUML, Islamabad


Note: RN=last two digit of your roll number
5. MATLAB M-file Function
Consider the following equation

y ( 0 ) −ζ w t
y (t)= n
e sin ⁡(w n √ 1−ζ 2∗t +θ),
√ 1−ζ
a. Write a MATLAB M-file function to obtain numerical values of y(t). Your function
must take y ( 0 ) , ζ , wn , t and θ as function inputs and y (t) as output argument.
b. Obtain the plot for y(t) for 0<t<10 with an increment of 0.1, by considering the
following two cases.

Case 1: y ( 0 ) =0.15m, w n=√ 2 rad/sec, ζ=3/2√ 2 and θ=0;


Case 2: y ( 0 ) =0.15m, w n=√ 2 rad/sec, ζ=1/2√ 2 and θ=0;
Note: Plagiarized data will get zero marks.
Lab Assignment
Make a neat lab report.
Conclusion
In this Lab we study the implementation and use of script, function, flow control.

LAB 3: Signals and their classification.


Objective:-
The objective of this lab is to introduce you to the classifications of signals and how these classes
of signals can be implemented in MATLAB.
Equipment required:-
 A computer
 MATLAB 15 or higher

Theory
Signals are the pattern of variation that contains some sort of information. Information may be
stored in memory or just transient information in real time as in communication systems.
There can be many classifications of signals; some of the classifications are listed below:

1. Continuous Time vs. Discrete Time Signals


2. Analog vs. Digital Signals
3. Periodic vs. Aperiodic Signals
4. Even vs. Odd Signals
5. Deterministic vs. Random Signals
6. Energy vs. Power Signals

1. Continuous Time vs. Discrete Time Signals.

Department of Electrical Engineering, NUML, Islamabad


a) Continuous Time Signals:
Continuous Time Signal is the one whose domain is uncountable, we don’t care about range.
For storing the continuous time signal you need infinite memory which is not possible in any
real system. So, finite no of samples of a continuous time signals are stored. For plotting the
continuous time signals we use plot command, which simply connects the values of
intermediate samples, gives us the illusion of continuous time signals. In MATLAB we can
plot any continuous time signal for example using plot
command as follows:
%Continuous Time Signal Example
A=2; %Amplitude
f=2; %Frequence
phase=pi; %Phase
t=(0:0.01:2*pi)/pi; %Horizontal time axis
plot(t,A*sin(2*pi*f*t+phase));
title('Example of Continuous Time Signal');
xlabel ('Time (pi Units)');
ylabel ('Amplitude');

b) Discrete Time Signals:


Discrete Time Signals are those signals which are purely based upon domain, whose domain is
countable. We don’t care about range of the signal. In MATLAB we can plot any discrete time
signal for example using stem command as follows:
%Discrete Time Signal Example
A=1; %Amplitude
f=1; %Frequence
phase=pi; %Phase
n=0:10; %Sample Number
stem(n,A*sin(f*n+phase));
title('Example of Discrete Time Signal');
xlabel ('n (Sample Number)');
ylabel ('Amplitude');

Department of Electrical Engineering, NUML, Islamabad


2. Analog vs. Digital Signal:
This classification of signal is purely based on range, we don’t care about the domain.
a) Analog Signals:
Analog Signals can take infinite values in range. In MATLAB we can plot any continuous
time signal for example. Asin (2πft+θ) using plot command as follows:
%Analog Signal Example
A=2; %Amplitude
f=2; %Frequence
phase=pi; %Phase
t=(0:0.01:2*pi)/pi; %Time axis
plot(t,A*sin(2*pi*f*t+phase));
title('Example of Analog Signal');
xlabel ('Time (pi Units)');
ylabel ('Amplitude');

We can also plot analog signal using stem command.


%Example of Discrete Time Analog Signal
A=2; %Amplitude
w=0.1; %Frequence
phase=pi; %Phase
n=(0:100); %Time axis
stem(n,A*sin(w*n+phase));
Department of Electrical Engineering, NUML, Islamabad
title('Example of Analog Signal');
xlabel ('Sample Number');
ylabel ('Amplitude');

b) Digital Signal:
Digital signal is the one which can take countable finite values in range. In MATLAB we
can plot digital signal for example a random bipolar data using stem or plot commands.
%Digital Signal Example
d=round(rand(1,100)); %Random Values
bd=2*d-1; %binary data
phase=pi; %Phase
n=1:100; %Time axis
stem(n,bd);
title('Example of Digital Signal');
xlabel ('Time');
ylabel ('Amplitude');

Square wave is another example of Digital signal.


%Digital Signal Example
A=1; %Amplitude
Department of Electrical Engineering, NUML, Islamabad
f=2; %Frequence
phase=pi; %Phase
t=(0:0.01:2*pi)/pi; %Horizontal time axis
plot(t,A*square(2*pi*f*t+phase));
axis([-0.1,2.1,-1.1,1.1]);
title('Example of Digital Signal');
xlabel ('Time (pi Units)');
ylabel ('Amplitude');

3. Periodic vs. Aperiodic Signals:


a) Periodic Signals:
A signal which repeats its pattern after a specific interval of time is called periodic signal. A
signal which does not repeat its pattern after a specific interval of time is called aperiodic
signal.

x[n± N ]=x [ n]
Where N is the fundamental time period.
In MATLAB we can generate a periodic signal using following code:
%Periodic Signal Example
A=1; %Amplitude
f=1; %Frequence
phase=pi; %Phase
n=0:10; %Sample Number
stem(n,A*sin(f*n+phase));
title('Example of Periodic Signal');
xlabel ('n (Sample Number)');
ylabel ('Amplitude');

Department of Electrical Engineering, NUML, Islamabad


b) Aperiodic Signals:
The opposite of a periodic signal is an aperiodic signal. An aperiodic function never
repeats, although technically an aperiodic function can be considered like a periodic
function with an infinite period.
In MATLAB we can generate an Aperiodic signal using following code:
%Aperiodic Signal Example
A=1; %Amplitude
f=1; %Frequence
phase=pi; %Phase
n=0:10; %Sample Number
plot(n,A*exp(f*n+phase));
title('Example of Aperiodic Signal');
xlabel ('n (Sample Number)');
ylabel ('Amplitude');

4. Even vs. Odd Signals


a) Even Signals:
If x(-n) = x(n) then signal is called even signal. Cosine function is an example of even signal.
%Even Signal Example
A=1; %Amplitude
f=1; %Frequence
phase=pi; %Phase
n=0:10; %Sample Number
Department of Electrical Engineering, NUML, Islamabad
plot(n,A*cos(f*n+phase));
title('Example of Even Signal');
xlabel ('n (Sample Number)');
ylabel ('Amplitude');
b) Odd Signals:
If x(-n) = -x(n) then signal is called odd signal. Sine function is an example of odd signal.
%Odd Signal Example
A=1; %Amplitude
f=1; %Frequence
phase=pi; %Phase
n=0:10; %Sample Number
plot(n,A*sin(f*n+phase));
title('Example of Odd Signal');
xlabel ('n (Sample Number)');
ylabel ('Amplitude');
5. Deterministic vs. Random Signals
a) Deterministic Signal:
A deterministic signal is one which can be completely represented by Mathematical equation
at any time. In a deterministic signal there is no uncertainty with respect to its value at any
time.
All the examples given above are of deterministic signals.
b) Random Signal:
Stochastic signals, or random signals, are not so nice. Random signals cannot be characterized
by a simple, well-defined mathematical equation and their future values cannot be predicted.
Rather, we must use probability and statistics to analyze their behavior. Also, because of their
randomness, average values from a collection of signals are usually studied rather than
analyzing one individual signal.

Example: Rolling a dice 1000 times.


one=0;two=0;three=0;four=0;five=0;six=0;%Possible Outcomes
a=ceil(6*rand(1,1000)); %1000 rolls of dice
for i=1:1000 %Counting each outcome
if(a(i)==1)
one=one+1;
end
if(a(i)==2)
two=two+1;
end
if(a(i)==3)
three=three+1;
end
if(a(i)==4)
four=four+1;
end
if(a(i)==5)

Department of Electrical Engineering, NUML, Islamabad


five=five+1;
end
if(a(i)==6)
six=six+1;
end
end
%Probability of each outcome
probDice(1)=one/1000;
probDice(2)=two/1000;
probDice(3)=three/1000;
probDice(4)=four/1000;
probDice(5)=five/1000;
probDice(6)=six/1000;
stem(probDice);%Plot each outcome
axis([0 7 0 0.25]);
xlabel('Numbers 1,2,3,4,5 and 6 on the Dice');
ylabel('Probability of 1,2,3,4,5 and 6 after 1000 experiments');
title('Probability of each number after roll of Dice 1000
times');
6. Energy vs. Power Signal:
a) Energy Signal:
A signal x(t) is said to be energy signal if and only if the total normalized energy is finite and
non-zero. Non-periodic signals are energy signals. Total energy of a signal x(t) can be
expressed as:
+T
E∞ = lim ∫ x ( t ) dt
2

T → ∞ −T

b) Power Signal:
The signal x(t) is said to be power signal, if and only if the normalized average power p is
finite and non-zero. Practical periodic signals are power signals. Total power of a signal
x(t) is given by:
+T
1
P∞ =lim ∫ x 2 ( t ) dt
T → ∞ 2T −T

Example: Following is example of Energy signal:

Let x (t)= {
2 ,|t|≤ 1
0 ,|t|>1

Using MATLAB Symbolic Maths, we can find its energy as following


syms t T
x=2;
E=limit((int(x^2,t,-1,1)),T,inf)
E =8

Department of Electrical Engineering, NUML, Islamabad


For an energy signal, power will always be equal to zero
P=limit((1/(2*T))*(int(x^2,t,-1,1)),T,inf)
P =0

Example: Following is the example of Power Signal


Let x ( t )= {2 ,−∞<t< ∞
syms t T
x = 2;
P = limit((1/(2*T))*(int(x^2,t,-T,T)),T,inf)
P =4

For a power signal, energy is always equal to .


E = limit((int(x^2,t,-T,T)),T,inf)
E =Inf

Example: Following is the example of a signal which is neither a power signal nor energy
signal for which we have Total energy and power equal to ∞ .
Let x ( t )= {t ,−∞<t <∞

syms t T
x=t;
E=limit((int(x^2,t,-T,T)),T,inf)
E = Inf
P=limit((1/(2*T))*(int(x^2,t,-T,T)),T,inf)
P = Inf

Power and Energy of Discrete Time Signals


For a Discrete Time Signal we simply replace integral with summation. In MATLAB symsum
command is used for summation.
Example: Find the energy of the following signal.
x[n]=sin(πn) -4≤ n ≤ 4
syms n T
E=limit((symsum(sin(n*pi)^2,n,-4,4)),T,inf)
E=
0
P=limit((1/(2*T))*(symsum(x^2,t,-T,T)),T,inf)
P=
4

Department of Electrical Engineering, NUML, Islamabad


Analysis
LAB WORKSHEET (Lab # 3)
1. Even and Odd Signals
Give two examples of Odd and Even signals each (other than those mentioned in the lab) and
plot them in MATLAB.
2. Periodic and Aperiodic Signals
Is the following signal periodic or Aperiodic?

{
x (t) cos ( t ) , t ≤ 0
sin ( t ) ,t >0
Plot the signal in MATLAB to verify your answer.
3. Energy and Power Signals
Find the energy and power of the following signals.
3
y ( t ) =t + 4 t ,−∞ <t< ∞

( ) π
y ( t ) =cos t ,−∞<t< ∞
4
4. Classification of Signals
Are y(t) and z(t) Energy signals or Power signals? Give reasons for your answer using the
results in last question.
5. Deterministic and Random Signals
Give an example for Deterministic and Random Signal each (other than those mentioned
in the lab) and plot them in MATLAB.

Lab Assignment
Make a neat Lab report.

Conclusion
In this lab we study and implement signals and their classification.

Department of Electrical Engineering, NUML, Islamabad


LAB 4: Operations on signals using MAtlab.

Objective:-
The objective of this lab is to introduce you to the operations of signals and how these operations
of signals can be implemented in MATLAB.
Equipment required:-
 A computer
 MATLAB 15 or higher

THEORY:
A single is classified with respect to its domain and range. Similarly operations on signals are
classified into two categories.

1. Operations on domain
2. Operations on Range

Both categories will be dealt in the current laboratory.

Operations on Domain
Domain operations are those which involve time axis or integer axis as main focus of operations.
Domain operations are classified into following four categories.
1. Time Shifting
2. Time Scaling
3. Time Reversal
4. Sampling

1. Time Shifting
Time Shift or delay operation shifts the signals to the desired delay. Given a
signal x(t ) , a shifted signal will be of the form y (t ) = x ( t- to) where to is the delay or shift in
time domain. Let Asin(2π ft) is the signal which is desired to be shifted by an amount to . Here is
the Matlab code for it.

Department of Electrical Engineering, NUML, Islamabad


% Time Delay/ Time Shifting
inc=0.1;
t=-10:inc:10;
f=0.1;
t0=2; % Shift Units
a=2; % Amplitude
x=a*sin(2*pi*f*t);
y=a*sin(2*pi*f*(t-t0));
subplot(311);
hold on;
plot(t,x);
plot(t,y,'r');
title('Original and Shifted Signal');
subplot(312);
plot(t,x);
title('Original SIgnal');
subplot(313);
plot(t,y);
title('Shifted SIgnal');

For discrete signal each sample of x( n) is shifted by an amount k to obtain the shifted sequence y (
n).
y (n ) ={ x (n-k )}
If we let m= n- k then n= m +k and we get
y (m +k ) ={ x (m )}

Matlab code for the function of time shift operation is as follows:

Department of Electrical Engineering, NUML, Islamabad


function [y,n]=sigshift(x,m,n0)
n=m+n0;
y=x;

2. Time Scaling
Operation of time scaling scales the time axis to a certain scale resulting in increasing or
decreasing the frequency of the signal which compresses or expands the signal on time
domain.General expression for the time scaled output is given below.

y(t)=x(αt)

Let Asin(2π ft) is the original signal on time scale. We scale the t domain by amount alpha and
beta. Alpha scaled signal will be compresses due to increment in frequency while beta scaled
signal will be expanded. Exampled is coded below.

%time Scaling
inc=0.1;
t=-10:inc:10;
f=0.1;
alpha=2; % Compression Units
a=2; % Amplitude
beta=0.5; % Expension units
x=a*sin(2*pi*f*t);
y=a*sin(2*pi*f*(alpha*t));
z=a*sin(2*pi*f*(beta*t));
subplot(311);
plot(t,x);
title('Original Signal');
subplot(312);
plot(t,y);
title('Time scaled Compressed SIgnal');
subplot(313);
plot(t,z);
title('Time Scaled Expanded SIgnal');

Department of Electrical Engineering, NUML, Islamabad


3. Time Reversal
Time Reversal operation flips each sample of the signal about t=0 or n=0 to
obtain a folded sequence.

y (n ) ={ x (-n)}

In Matlab fliplr(x) function is used to flip the sample values and –fliplr(x) is used to flip the
indices
inc=0.1;
t=-10:inc:10;
f=0.1;
a=2; % Amplitude
x=a*sin(2*pi*f*t);
rx=fliplr(x);
rt=-1*fliplr(t);
l=length(x);
subplot(311);
hold on;
plot(t(l/2:l),x(l/2:l));
plot(rt(1:l/2),rx(1:l/2),'r');
title('Original and reflected Signal');
subplot(312);
plot(t,x);
title('Original SIgnal');
subplot(313);
plot(rt,rx);
title('Reflected/flipped SIgnal');

Department of Electrical Engineering, NUML, Islamabad


A Matlab function to implement the signal flipping is given below.

function [y,n]=sigfold(x,m)
y=fliplr(x) %flips the amplitude levels
n=-1*fliplr(n) %flips the indices on negative sides

4. Sampling
Sampling is the reduction of a continuous signal to a discrete 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 refers to a value or set of values at a point in time and/or space.


Let x = sin(2 π ft ) be the signal with highest frequency component f. We sample the signal at
different rates as follows.

% Sampling of single frequency component


f=1;
fs=10*f; %Sampling frequency
ts=1/fs; % Sampling Interval
t=-1:ts:1;
x=sin(2*pi*f*t);
stem(t,x);

Department of Electrical Engineering, NUML, Islamabad


Following example shows the sampling of the given signal at different rates. The output graph
shows how sampling rate predicts the signal behavior and loss of information.
% Sampling of single frequency component at different rates
f=10;
fs1=2*f; %Sampling frequency
fs2=10*f;
fs3=0.5*f;
ts1=1/fs1; % Sampling Interval
ts2=1/fs2;
ts3=1/fs3;
t1=-1:ts1:1;
t2=-1:ts2:1;
t3=-1:ts3:1;
x1=sin(2*pi*f*t1);
x2=sin(2*pi*f*t2);
x3=sin(2*pi*f*t3);
subplot(311); stem(t1,x1);
title('sampling at double rate');
subplot(312);stem(t2,x2);
title('sampling at 10 times frequency');
subplot(313);stem(t3,x3);
title('sampling at 0.5 times frequency');

Department of Electrical Engineering, NUML, Islamabad


Operations on Range

Range operations involve amplitudes of the signal as major focus of operations. They are
classified as

1. Amplitude Scaling
2. Addition of Signals
3. Subtraction of signals
4. Multiplication of Signals
5. Derivative of signals

1. Amplitude Scaling
Amplitude scaling rescales the amplitude of the signal. As a result signal may be amplified or
attenuated. Given a signal x = A sin(2 π ft ) where A is the amplitude of the signal. We can
rescale the amplitude by some constant multiplier alpha or beta. Amplitude scaled output will
be
y = α{ A sin(2 π ft )}

Code given below scales the amplitude by constant alpha and beta which amplifies and
attenuate the signal respectively.
% Amplitude Scaling
t=-1:0.01:1;
f=1;
a=1; % Amplitude
alpha=2; % Amplitude scale
beta=0.5; % Attenuated scale
x=a*sin(2*pi*f*t);
Department of Electrical Engineering, NUML, Islamabad
y=alpha*sin(2*pi*f*t);
z=beta*sin(2*pi*f*t);
subplot(311);
plot(t,x);
title('Original Signal');
subplot(312);
plot(t,y);
title('Amplified Signal');
subplot(313);
plot(t,z);
title('Attenuated SIgnal');

A Matlab function to implement the Amplitude scaling is given below.

function y=sigscale(x,alpha)
y=alpha*x;

2. Signal Addition
This is a sample by sample addition given by
{ x1(n )} +{ x2( n)} { x1( n) + x2(n )}

It is implemented in Matlab using + operator however this requires the lengths of the vectors
to be same. But if the signals are of different lengths or if the sample positions are different for
same length sequences, then we cannot directly use the ‘+ ‘operator. We first have to augment
the x1(n) and x2(n) so that we have the same position vector and hence the same length. This
involves MATLAB indexing operations. Logical operators of ‘&’,’<’, :>’ and find functions
are used to make x1(n) and x2(n) of same lengtha. The following function called sigadd
performs the said operation.

Department of Electrical Engineering, NUML, Islamabad


function [y,n]=sigadd(x1,n1,x2,n2)
n=min(min(n1),min(n2)):max(max(n1),max(n2));
y1=zeros(1,length(n)); %initialization
y2=y1;
y1(find((n>=min(n1)) & (n<=max(n1))==1))=x1;
y2(find((n>=min(n2)) & (n<=max(n2))==1))=x2;
y=y1+y2;

Example:
Let x1 =[ 1 2 3] having indices as n1 =[- 1:1]
And x2= [5 6 7 8] = having indices n2 =[1: 4]
To add the sequences, we use the function as below.
>> [y,n]=sigadd(x1,n1,x2,n2)

3. Signal Subtraction
Sequence/Signals subtraction is similar to addition of signals except the function name and
operator sign. Example is given below.

% Subtraction of sgnals
function [y,n]=sigsub(x1,n1,x2,n2)
n=min(min(n1),min(n2)):max(max(n1),max(n2));
y1=zeros(1,length(n));
y2=y1;
y1(find((n>=min(n1)) & (n<=max(n1))==1))=x1;
y2(find((n>=min(n2)) & (n<=max(n2))==1))=x2;
y=y1-y2;

Example:
Let x1= [ 1 2 3] having indices as n1 =[- 1:1]
And x2= [5 6 7 8] having indices n2= [1: 4]
To subtract the sequences, we use the function as below.
>> [y,n]=sigsub(x1,n1,x2,n2)

4. Signal Multiplication
Multiplication of signals or sequences involves sample by sample multiplication. After making
the lengths of the vectors same, we multiply the signals using ‘.’ (dot) operator.
Here is the example.

% Multiplication of sgnals
function [y,n]=sigmul(x1,n1,x2,n2)
n=min(min(n1),min(n2)):max(max(n1),max(n2));
y1=zeros(1,length(n)); %initialization
y2=y1;
y1(find((n>=min(n1)) & (n<=max(n1))==1))=x1;
y2(find((n>=min(n2)) & (n<=max(n2))==1))=x2;
y=y1.*y2; % Element wise multiplication

Department of Electrical Engineering, NUML, Islamabad


Example:
Let x1= [ 1 2 3] having indices as n1 =[- 1:1]
And x2= [5 6 7 8] having indices n2= [1: 4]
To multiply the sequences, we use the function as below.
>> [y,n]=sigmul(x1,n1,x2,n2)

5. Derivative of Signal
Derivative of a given signal is calculated using symbolic Mathematics. Following is the
example to find the derivative of the signal.
%Derivative of signal
syms x y t f
x=sin(t);
y=diff(x);
subplot(211);
ezplot(t,x); %command to plot in syms mode
subplot(212);
ezplot(t,y);

Analysis
LAB WORKSHEET (Lab # 4)

1. Let x (n )= {1, 2,3, 4,5,6,7,6,5, 4,3, 2,1}. Determine and plot the following sequences.
Department of Electrical Engineering, NUML, Islamabad
a) x1(n )= 2 x ( n -5) -3x (n+ 4)
b) x2(n )= x(3 - n) + x(n)x(n- 2)

2. Write a Matlab function named multioperations which returns the following output on
graph simultaneously.

a. Amplitude scaled signal


b. Time Scaled signal
c. Time Shifted Signal

Alpha, beta, gamma are the variables used for defining the scales for shifting, time scaling and
amplitude scaling respectively. Take the input signal
A sin(2πfn +φ). Alpha, beta and gamma must be taken from user on run time.

3. Write a Matlab function named multioperators which returns the following output on graph
simultaneously.

a. Sum of the signals


b. Difference of the signals
c. Product of the signals

Take input from user about the operation. Then use switch statement to perform the respective
operations. Use Input() function to take input from the user.

Lab Assignment
Make a neat Lab Report.
Conclusion
Signal operations is implemented on Matlab.

LAB 5: Study basic signals using matlab.

Department of Electrical Engineering, NUML, Islamabad


Objective:-
The objective of this lab is to introduce you to the basic signals and how these basic signals can be
implemented in MATLAB.
Equipment required:-
 A computer
 MATLAB 15 or higher

THEORY:
This lab is about the basic sequences and signals and their use in generating other
sequences. Followings are the signals that we will study in this lab.
1. Unit Impulse
2. Unit Step
3. Exponential Signals
4. Unit Ramp
5. Rectangular Pulse (Rect Signal)
1. Unit Impulse
Unit Impulse is defined as following

{
δ ( n )= 1 n=0
0n≠0
The impulse exists only on the origin point (zeroth index) and is zero elsewhere. In Matlab. we
implement the sequence as follows.

function [x,n]=impulsesig(l,no)
n=-l:l; % defines n axis in symmetric length
x=zeros(1,length(n)); %initialization
x(l+no+1)=1;

Example:
In Command window we call this function as

[x,n]=impulsesig(6,2)
Stem(n,x)
And following result is produced.

Department of Electrical Engineering, NUML, Islamabad


The above code works by creating a symmetric axis about zero that may not be the case always. In
case where different length of the axis is required and impulse is to be placed in same pattern, we
do it as follows.

function [x,n]=impseq(n1,n2,n0)
%Generates x(n)=delta(n-n0); n1<=n<=n2
n=n1:n2;
x=[(n-n0)==0];

Example:
In command Window, let we want a pulse at n0=2 whereas our axis starts from -2 and ends at 6.
We call this function as

[x,n]=impseq(-2,6,1);
Stem(n,x)

Following result is produced.

2. Unit Step Sequence


Unit Step signal is defined as follows
Department of Electrical Engineering, NUML, Islamabad
{
µ ( n )= 1 n≥ 0
0 n< 0
The signal has one amplitude on positive axis starting from zeroth index. Matlab code for the said
signal is given below.

function [x,n]=dus(l,no)
n=-l:l;
len=length(n);
x=zeros(1,length(n));
x(l+no+1:len)=1;
end

The code produces the symmetric axis in the same way as for the unit impulse. Only difference is
that now a vector of 1s is placed as amplitude in place of single impulse. In command window run
the following example.

[x,n]=dus(6,1);
Stem(n,x)
Following output will be produced.

For non-symmetric n axis we can write the code as follows.


function [x,n]=step(n1,n2,n0)
n=n1:n2;
x=[(n-n0)>=0];
end
Example: let no=1; n1=-2; and n2= 10;
[x,n]=step(no,n1,n2);
Stem(n,x)
We will see the following output.

Department of Electrical Engineering, NUML, Islamabad


3. Exponential Signals
A real exponential is defined as follows.
X(n)=a n ∀ n ∈real

Example: X(n)=0.9n 0 ≤ n ≤10


We do it in Matlab as
n=0:10;
x=0.9.^(n);
plot(n,x)

The shape of the real exponential varies as decaying or rising exponentials. Depending
upon the real constant, signal decays or rises.

4. Unit Ramp
Ramp signal is defined as

Department of Electrical Engineering, NUML, Islamabad


r ( t )= {0 othewise
t t ≥0

The amplitude values vary as domain increases. Ramp signals exts on positive side only.
Matlab Code for Unit ramp is given below.
t=0:0.01:10;
x=t;
plot(t,x)

Output signal is given below.

Another approach is to generate a ramp signal on shifted point or interval. Function for the
shifted ramp is given below.

function [x,n]=rampseq(no,n1,n2)
%produces ramp sequence on axis n and starting from no
n=n1:n2;
x1=[(n-no)>=0];
x=x1.*(n-no);
end
Example:
[x,n]=rampseq(1,-5,6)
Stem(n,x)
Output is shown below.

Department of Electrical Engineering, NUML, Islamabad


5. Rectangular Pulse
Rect signal is defined as

{
rect = 1−1/2≤ t ≤ 1/2
0 othewise
Rect signal produces a rectangular pulse of the width equal to the time interval with half of the
width lying on negative side and half on positive side.
Matlab code is given below.
function [x,n]=rectseq2(t,n1,n2)
n=n1:n2;
x=[(n+(t/2))>=0 & (n-(t/2))<=0];
end
Example: In command window use the following example
[x,n]=rectseq(2,-3,5);
stem(n,x);

Department of Electrical Engineering, NUML, Islamabad


Analysis
LAB WORKSHEET (Lab # 5)
1. Use the impulse and step functions to implement the function y[n] given by the relation.
Implement amplitude scaling through sigscale function.
a. y[n]=2δ[n+3]+5δ[n]+ 6δ[n+5]- 7δ[n-2]
Use L=6 for y[n].

2. Use the functions for signal flipping, amplitude scaling, signal addition and ramp to generate
the following sequence.

3. Use rect(t) function from your manual and generate a periodic rectangular signal. Take width
of the pulse =2. -3≤ n ≤ 5.

Lab Assignment
Make a neat Lab Report.
Conclusion
Basic Signals has been studied and implemented in Matlab.

Department of Electrical Engineering, NUML, Islamabad


LAB 6: Study Convolution & Properties of LTI System using
MATLAB.

Objective:-
The objective of this lab is to introduce you to the properties of LTI system and how these
properties can be implemented in MATLAB.
Equipment required:-
 A computer
 MATLAB 15 or higher

THEORY:
This experiment is designed to familiarize the students with the basic concept of system
characteristics. In this experiment following characteristics of the system will be addressed,
 Static and Dynamic Systems
 Causality
 Time Invariance
 Linearity
 Stability
System Review

1. Static (Memoryless) and Dynamic (with Memory) Systems


A system is static or memoryless if for any input signal x(t) or x[n] the corresponding
output y(t) or y[n] depends only on the value of the input signal at the same time. In
simple words, output of a sytems depends only on present values of input. A nonstatic
system is called dynamic or dynamical.
Example
Department of Electrical Engineering, NUML, Islamabad
Using the input signal x[n] = u[n] - u[n-1] find out if the systems described by the i/o
relationships y[n] = 3x[n] and y[n] = x[n] + x[n-1] are static or dynamic. Use -3≤n≤3.

First plot represents the input signal x[n]. Second row of the plot represent first system i.e:
y[n] = 3x[n]. As output of this system depends only on the value of the input at the same time.
Hence, it is a static (or memoryless) system.
To determine if the second system described by the i/o relationship y[n] = x[n] + x[n-1] is
static or dynamic, we can simply it and write it as y[n] = u[n] – u[n-2]. The values of y[n]
depend on past values of x[n] so the system is dynamic.

Department of Electrical Engineering, NUML, Islamabad


2. Causal and Noncausal Systems
A system is causal if the system output y(t0) at time t = t0 does not depend on values of the
input x(t) for t > t0. In other words, for any input signal x(t), the corresponding output y(t)
depends only on the present and past values of x(t). So, if the input to a causal system is zero
for t < t0 the output of this system is also zero for t < t0. Correspondingly, a discrete-time
system is causal if its output y[n 0] at time n = n0 depends only on the values of the input signal
x[n] for n ≤ n0. All natural systems are causal. However, in engineering there are many
noncausal systems. For example, off-line data processing is a noncausal system. In simple
words, output of a causal system is independent of future values of input. While for non-
causal systems, the output depends upon the future value of the input at any instant of time.
Example
Suppose that a system S1 is described by the y[n]=x[n+1] while a system S2 is given by
y[n] =x[n-1]. Using the input signal x[n]=u[n]-u[n -1] find out if the two systems are
causal. Use -3≤n≤3.

First plot represents the output of system 1. The input x[n] is zero for n < 0 but the output
Department of Electrical Engineering, NUML, Islamabad
y[n] is nonzero for n < 0, i.e., y[n] depends on future values of x[n]; thus system S1 is not
causal. Second row of the plot represent second system i.e: y[n] = x[n-1]. The output is zero
for n < 1, i.e., y[n] depends only on past values of x[n]; thus system S2 is causal.

3. Time-Invariant and Time-Variant Systems


A system is time invariant, if a time shift in the input signal results in the same time shift in
the output signal. In other words, if y(t) is the response of a time-invariant system to an input
signal x(t), then the system response to the input signal x(t-t 0) is y(t-t0). The mathematical
expression is: y(t-t0) = S{x(t -t0)}.
Equivalently, a discrete-time system is time or (more appropriately) shift invariant if y[n-n 0]=
S{x[n-n0]}.
From above experession, we conclude that if a system is time invariant, the amplitude of the
output signal is the same independent of the time instance the input is applied. The difference
is a time shift in the output signal. A non-time-invariant system is called timevarying or time-
variant system.
Example
Suppose that the response of a system S to an input signal x[n] is y[n]=ne(-n)x[n].
Determine if this system is time invariant by using the input signal x[n] = u[n] - u[n-5].
Use -10≤n≤10.

Department of Electrical Engineering, NUML, Islamabad


Input signal is plotted in the first row of above figure. Then first we compute and plot the
system response y[n] to the given input signal x[n], as shown in second row. Next the
computed output y[n] is shifted by 3 units to the right to represent the signal y1[n] = y[n-3], as
shown in third row. Then input signal x[n] is shifted 3 units to the right to represent the signal
x[n-3], as shown in fourth row. Next the system response y2[n] =S{x[n-3]} is computed and
plotted, as shown in fifth row. If the two derived system responses are equal, the system under
consideration is time invariant.

4. Linear and Nonlinear Systems


Let y(t) denote the response of a system S to an input signal x(t), that is, y(t) = S{x(t)}.
System S is linear if for any input signals x1(t) and x2(t) and any scalars a1 and a2 the
following relationship holds:

In other words, the response of a linear system to an input that is a linear combination of two
signals is the linear combination of the responses of the system to each one of these signals.
The linearity property is generalized for any number of input signals, and this is often referred
to as the principle of superposition. The linearity property is a combination of two other
properties: the additivity property and the homogeneity property. A system S satisfies the
additivity property if for any input signals x1(t) and x2(t):
Department of Electrical Engineering, NUML, Islamabad
while the homogeneity property implies that for any scalar a and any input signal x(t):

Example
Let x1[n] = u[n]-u[n-1] and x2[n]=u[n]-u[n-2] be input signals to the system y[n]=2x[n].
Determine if the linearity property holds for this system. To examine if the system is
linear, use the scalars a1 = 2 and a2 = 3. The time interval considered is -3≤n≤3.

Input signals x1[n] and x2[n] are plotted in the first two rows of the above figure. Then these
inputs (x1,x2) are passed through the system and output y[n] is shown in row 3. Then x1[n] is
only passed through system to get y1[n], as shown in row 4. Similarly, row 5 shows the output
of system (y2[n]) for x2[n]. In the end, y1[n] and y2[n] are summed. The two graphs obtained
are identical, hence, the two sides of aforementioned equation are equal. Therefore, the
system described by the i/o relationship y[n] = 2x[n] is linear.

Department of Electrical Engineering, NUML, Islamabad


5. Stable and Unstable Systems
The practical meaning of a stable system is that for a small applied input the system
response is also small (does not diverge). A more formal definition is that a system is
stable or bounded-input bounded-output (BIBO) stable if the system response to any
bounded-input signal is a bounded-output signal.
Example
Input signal x(t)=cos(2pt) is applied to two systems y1(t)=x 2(t)and y2(t)= tx(t). Determine
if these two systems are stable. The time interval considered is 0≤t≤10.

Input signals x[n] is plotted in the first row of the above figure. The input signal is bounded as
1≤x(t)≤1. Then the input is passed through the first system i.e. y1(t)=x 2(t) and output y1(t) is
shown in second row. The output signal y1(t) is bounded as 1≤y1(t)≤1. Hence, the system one
is BIBO stable. In the end the input is passed through the second system i.e. y2(t)= tx(t) and
output y2(t) is shown in the third row. The output signal y2(t) is not bounded as its amplitude

Department of Electrical Engineering, NUML, Islamabad


is getting larger as time passes. Hence, the second system is not BIBO stable.

Analysis
LAB WORKSHEET (Lab # 6)
1. Determine if the discrete-time system y[n] =x 2[n] is time invariant. Use the input signal
x[n] = 0.8n(u[n] - u[n 5]).
2. Consider a system y[n] = x[2n]. Find out if this is a time invariant system by using the
input signal x[n] =u[n+2] – u[n-2].
3. Let x1[n] = u[n]-u[n-1] and x2[n]=u[n]-u[n-2] be input signals to the system y[n]=x 2[n].
Determine if the linearity property holds for this system. Use the scalars a1 = 2 and a2 = 3.
The time interval considered is -3≤n≤3.
4. Determine if the discrete-time system described by the i/o relationship y[n] = x 2[n] is static
or dynamic. Use the input signal x[n] = [0 1 2 3 4]. The time interval considered is -
1≤n≤3.
Lab Assignment
Make a neat Lab Report.
Conclusion
Properties of LTI system has been studied and implemented in Matlab.

Department of Electrical Engineering, NUML, Islamabad


LAB 7: Periodicity, harmonics and Fourier Series using Matlab.

Objective:-
The objective of this lab is to introduce you to the fourier series and peridic signals and how
fourier series can be implemented in MATLAB.
Equipment required:-
 A computer
 MATLAB 2015 or higher

THEORY:
The French Mathematician Joseph Fourier founded that any periodic waveform, can be expressed
as a series of harmonically related sinusoids i.e., sinusoids whose frequencies are multiples of a
fundamental’s frequency (or first harmonic). Up to this point, all signals were expressed in the
time domain. With the use of the Fourier series, a signal is expressed in the frequency domain and
sometimes a frequency representation of a signal reveals more information about the signal than
its time domain representation.

Department of Electrical Engineering, NUML, Islamabad


Now let us get to importance of Fourier Series.
1. First and foremost, it tells you what frequencies are present in your signal (periodic) and in
what proportions.

Example: Have you ever noticed that each of your phone's number buttons sounds
different when you press during a call and that it sounds the same for every phone model?
That is because they're each composed of two different sinusoids which can be used to
uniquely identify the button. When you use your phone to dial some number, the way that
the other party knows what keys you pressed is by doing a Fourier transform (extension of
Fourier Series for Non-Periodic Signals) of the input and looking at the frequencies
present.

2. By being able to split signals into their constituent frequencies, one can easily block out
certain frequencies selectively by nullifying their contributions.

3. A shifted (delayed) signal in the time domain manifests as a phase change in the frequency
domain. While this falls under the elementary property category, this is a widely used
property in practice, especially in imaging and tomography applications.
Example: When a wave travels through a heterogenous medium, it slows down and
speeds up according to changes in the speed of wave propagation in the medium. So by
observing a change in phase from what's expected and what's measured, one can infer the
excess time delay which in turn tells you how much the wave speed has changed in the
medium. This is of course, a very simplified layman explanation, but forms the basis for
tomography.

Trigonometric Fourier Series Expansion

Department of Electrical Engineering, NUML, Islamabad


Example

Department of Electrical Engineering, NUML, Islamabad


Example

2
t

3
a o=
2
a n=0

{
0 ,∧n=even
b n= 6
,∧n=odd
πn

Now equation (A) can be written as


3 6 6 6
x ( t )= + sin ( t ) + sin ( 3 t ) + sin ( 5 t ) …
2 π 3π 5π

Department of Electrical Engineering, NUML, Islamabad


Thus, the waveform only contains the odd harmonics i.e. 1w0, 3w0, 5w0, 7w0, 9w0 and so on.

MATLAB IMPLEMENTATION

close all;clc;clear all


tmax= 2*pi;
Har = 20;
wo= 1;
t=-tmax : 0.01 : tmax;
ao=3/2;
temp=0;
for n=1:2:har
X = (6./(n*pi)) .* sin(n*wo*t);
temp=X+temp;
end

Now you can increase the number of harmonics and analyze that the waveform becomes
more closer to the ideal one.
Example: Expand trigonometric Fourier series of signal x(t) = e-t, 0 ≤ t ≤3.

Department of Electrical Engineering, NUML, Islamabad


Department of Electrical Engineering, NUML, Islamabad
Analysis
LAB WORKSHEET (Lab # 7)

Q3: Generate square wave using below equation for following number of harmonics

10,20,100. Do use subplots.

x (t)=
4
π { 1 1
cos ( wt )− cos ( 3 wt )+ cos ( 5 wt ) … … … … …
3 5 }
Lab Assignment
Make a neat Lab Report.
Conclusion
Priodicity of signals has been studied and fourier series has been studied and implemented in
Matlab.
Department of Electrical Engineering, NUML, Islamabad
LAB 8: Study Fourier transform using Matlab.

Objective:-
Main objective of the lab is to seek the concept of transformation of a time domain signal to
frequency domain using Fourier transformation and its analysis. In the last, we will find the
frequency response of a certain system over a range of frequencies.

Equipment required:-
 A computer
 MATLAB 2015 or higher

THEORY:
Fourier Transform
Fourier Transformation transforms a composite time domain signal to frequency domain
(complex) which shows the frequency components present in the system. The system can easily
be analyzed through this transform. Fourier Transform falls in two types
1. Continuous time Fourier transform
2. Discrete Time Fourier transform
We will discuss them one by one
Continuous time Fourier transform
CTFT is defined by the following relation.

Inverse Fourier transform transforms the signal back into time domain and give mathematically as

In Matlab we implement CTFT using symbolic math toolbox. Fourier and Fourier are the two
functions used for Fourier and inverse furrier transform.

Example:
Find the Fourier transform of the following signal.

x (t)= δ (t)

Department of Electrical Engineering, NUML, Islamabad


Matlab
syms t
ft=dirac(t);
fw=fourier(ft);
pretty(fw)

Example
To find the CTFT of a unit step function we proceed as follows

x (t) =µ(t)
Matlab
u=sym('heaviside(t)');
fw=fourier(u);
pretty(fw)

Example
Find the CTFT of x (t) = e−t / 2
Matlab
syms f t
f=exp(-t^2/2);
ft=fourier(f);
pretty(ft);
f=ifourier(ft)
pretty(f)
Discrete Time Fourier Transform
Discrete Time Fourier transform is defined as below

As compared to CTFT, DTFT deals with finite discrete time signals. Discrete time signals can be
of infinite or finite number of samples. We deal with both of them one by one.
DTFT for infinite duration signals
Let us take the following example for discrete signal having infinite number of samples.
Fourier transform of the discrete signal x(n)= (0.5)nµ(n) can be calculated as

¿= ∑ (0.5) µ( n)e
jwn n − jwn
X(e
n=−∞

X(e jwn ¿=∑ (0.5) e
n − jwn

n=0

Department of Electrical Engineering, NUML, Islamabad



X(e jwn ¿=∑ (0.5 e
− jw n
)
n=0
1
X(e jwn ¿= − jw
1−0.5 e
jw
e
X(e jwn ¿= jw
e −0.5
If x(n) is of infinite duration, then Matlab can not be used directly to compute X(e jw ¿ . However
we can evaluate the expression X(e jw ¿ over [0, π ] frequencies and plot the magnitude and phase
(or real and imaginary parts).
Following is the code and output for the Fourier transform evaluation of the above signal.

%Fourier Transform Evaluation


w=[0:1:500]*pi/500;
x=exp(j*w)./(exp(j*w)-0.5);
magx=abs(x);
angx=angle(x);
realx=real(x);
imagx=imag(x);
subplot(221);
plot(w/pi,magx);
grid;
xlabel('frequency in pi units')
ylabel('Magnitude')
title('Absolute Value');
subplot(222);
plot(w/pi,imagx);
grid;
xlabel('frequency in pi units')
ylabel('Magnitude')
title('Imaginary value');
subplot(223);
plot(w/pi,realx);
grid;
xlabel('frequency in pi units')
ylabel('Magnitude')
title('real value');
subplot(224);
plot(w/pi,angx);
grid;
xlabel('frequency in pi units')
ylabel('Magnitude')
title('imagninary value');

Output is shown below

Department of Electrical Engineering, NUML, Islamabad


DTFT for finite duration signals
If x(n) is of finite duration then X(e jwn ¿ can be computed at any frequency w. if we evaluate X(
e ¿ at equidistant frequencies between [0, π ] then expression for X(e ¿ can be implemented as
jwn jwn

matrix multiplication operation.


Let us assume that the signal x(n) has N samples between n1 ≤ n≤ n N and that we want to evaluate
the X(e jw ¿ at
π
ω= ∗K where K=0,1,…M
M
Which are (M+1) equispaced frequencies between [0, π ]. Expression for X(e jw ¿ can be written as

N π
−j kn
X(e jwk ¿=∑ e M
x (n)
n=l
jwk
Where X(e ¿ and x(n) are evaluated as column vectors X and x respectively, we have
X=Wx

Where W is an (M+1)xN matrix given by


π
W=e− j M kn Where n1 ≤ n≤ n N and K=0,1,…M
Furthermore n and k are taken as row vectors. Therefore taking transpose of above equation
π T
w=[exp(− j k n )]
M

Department of Electrical Engineering, NUML, Islamabad


In Matlab we take sequence and indices as row vectors so we can write the final expression for X(
jwn
e as

X= x*exp(- j* pi/ M).^( n’* k)


Where n=n1 : n N and k=0:M

Example
Find the DTFT for the following discrete time signal

Matlab code for the above signal is given below.

_n=-1:3;
y=1:5;
k=0:500;
w=(pi/500)*k;
x=y*exp(-j*pi/500).^(n'*k);
magx=abs(x);
angx=angle(x);
realx=real(x);
imagx=imag(x);
subplot(221);
plot(w/pi,magx);
grid;
xlabel('frequency in pi units')
ylabel('Magnitude')
title('Absolute Value');
subplot(222);
plot(w/pi,imagx);
grid;
xlabel('frequency in pi units')
ylabel('Magnitude')
title('Imaginary value');
subplot(223);
plot(w/pi,realx);
grid;
xlabel('frequency in pi units')
ylabel('Magnitude')
title('real value');
subplot(224);
plot(w/pi,angx);
grid;
xlabel('frequency in pi units')
Department of Electrical Engineering, NUML, Islamabad
ylabel('Magnitude')
title('imagninary value');
Output is

Analysis
LAB WORKSHEET (Lab # 8)
1. Study and implement Matlab command fft. Show its magnitude plots.

Lab Assignment
Make a neat Lab Report.

Conclusion
Fourier and inverse fourier transform has been studied and implemented in Matlab.

Department of Electrical Engineering, NUML, Islamabad


LAB 9: Open Ended Lab.

Objective:-
The objective of this lab is to introduce you to the correlation of signals and how correlation can
be implemented in MATLAB.

Equipment required:-
 A computer
 MATLAB 2015 or higher

Detect the Presence and Location of Target by Transmitting a Sound Signal


Introduction:
In this Lab, you are required to study correlation. Correlation is used to calculate the similarity
between two signals and this information is further used to achieve various useful purposes.
Correlation involves its application in areas such as radar, sonar, digital communication, image
processing, and many more and its mathematical formulation is given as:

In this lab, we will demonstrate the application of correlation in finding a target i.e. we will detect
the presence and location of the target by transmitting a Sound Signal. A sound signal is
transmitted using speakers and the mic is placed in parallel to speakers nearby. Mic receives the
output signal which contains the original signal, reflected signal, and noise.

After correlation, the highest peak represents the correlation of the original part of the received
signal with the original signal. The next peak represents the cross-correlation of the original signal
with echoed part of the received signal. The distance between these two peaks represents the
number of samples the echoed signal is delayed in consequence of how much far is the target.

Using equation S=vt where S is the distance, v is the velocity of sound which is 330 m/s and t is

the time which the signal takes to travel i.e. from transmitter to target.

Department of Electrical Engineering, NUML, Islamabad


( number of samples the signal is delayed )
Time delay=
sampling frequency

As this is the round-trip time so we divide it by 2 to get the value of t.

t= Time delay/2

So the distance of the target = 330 x t


Signals can be used:
 Chirp
 Impulse
 Step etc

Results and Observation:


Submit a complete report containing results (code and description), observations, findings, and
suggestions.

Department of Electrical Engineering, NUML, Islamabad


LAB 10: Study Sound Manipulation and playback using Matlab.

Objective:-
Objectives of this lab are twofold: 1) to understand manipulation of audio signals by applying
different operations, and 2) to prepare base lab for upcoming labs such as Discrete Fourier
transform (DFT) and digital filtering – where we will learn ways to analyze the frequency
contents of the audio signals and learn how to remove noise from the audio files.
Equipment required:-
 A computer
 MATLAB 15 or higher

THEORY:
Sound Manipulation
Since MATLAB treats all the inputs and output as matrices/vectors, therefore the manipulation
of an audio signal is no different than altering the elements of matrices. Similar is the case for
images and videos. When you will read an audio file either it be your own recording or any
pre-recorded sound signal, you will notice it’s just a matrix.

To read audio file from your computer use following command:


audioread(FileName)
Example: Let’s say we want to read a digital sound file named “S1.wav”, so that we can then
listen to it, plot it, manipulate, etc.
clc;clear all;close all
% Reading Audio File:
[Y,fs]=audioread('S1.wav'); //here you have to first set the path of MATLAB same as that of audio file
S1.wav.

% Calculating Total Time of Signal


time=(1/fs)*length(Y); // its explained in equation 1 below.

% plotting
t=linspace(0,time,length(Y));
plot(t,Y)
% Reading Audio File:
load handel
sound(y,Fs);
% Calculating Total Time of Signal

Department of Electrical Engineering, NUML, Islamabad


time=(1/Fs)*length(y); %its explained in equation 1 below.

% plotting
t=linspace(0,time,length(y));
plot(t,y)

The array Y now contains the sound data and fs is the sampling frequency. You will notice that,
Y has dimensions of (73113x1). Here 73113 is the number of samples in “handel.wav” and 1
represents that it’s a mono sound. I am sure you have heard the terms: “stereo” and “mono”. If
not, lets dig-in a bit. In simple words, with stereo you receive information in one ear that is
somewhat different to information received by the other. With mono audio your ears are receiving
100% of the same information. The difference is in the number of channels (signals) used. Mono
uses one, stereo uses more than one. In monaural sound one single channel is used. It can be
reproduced through several speakers, but all speakers are still reproducing the same copy of the
signal. In stereophonic sound more channels are used (typically two). You can use two different
channels and make one feed one speaker and the second channel feed a second speaker (which is
the most common stereo setup). This is used to create directionality, perspective, space. Let’s
understand from the figure below.

Figure 1: mono vs stereo


Now coming to second
part of our audio signal and that is sampling frequency (fs). In simple words, Sampling frequency
or Sampling Rate is the number of samples per second. That is, when we convert an analog
signal to digital signal, as analog signal is a continuous function of time, we take only its finite
samples (don’t worry if you are unable to grasp sampling concept 100% here, we have a separate
lab on Sampling). In our case you can see that fs is equal to 8123 i.e. (8123 samples/second).
Equation 1 is used to calculate the total time of signal:

Length of Audio Signal


Total Time= (1)
Sampling Frequency

Department of Electrical Engineering, NUML, Islamabad


Now let’s see how equation 1 is working. As I mentioned above that, fs is telling us number of
samples selected (recorded) per second. So, let’s suppose that fs = 5. It means, we are recording 5
samples/second. So, if I record a signal for 10 seconds, total number of samples will be? Yes, you
are right, total number of samples will be given by: (Sampling frequency) * (time of recording).
In our case, it will be: 5*10 = 50 samples in total. So, equation “1” is just manipulation of above-
mentioned expression, I have only shifted Time on left side of the equation. By using above
mentioned equation time of audio signal came out to be 9 seconds. You can play audio in any
player (such as VLC) and make sure its total time.

Figure 2. Time response of input voice signal

Let’s listen to the sound signal now (plug in your headphones). Enter these below
mentioned commands:

soundsc(Y,fs)
In case the above command doesn’t work (depending upon the MATLAB version) you can use
following commands:
playerObj = audioplayer(Y,fs);
play(playerObj);

Reverse Playing

To play the sound backwards, we simply reverse the order of the numbers in the arrays. Let’s
experiment with a small array. Type in the following commands:
Department of Electrical Engineering, NUML, Islamabad
y=[1;2;3;4;5]
y2=flipud(y)

Note that flipud stands for flip upside-down which flips your array y and stores the inverted
array in y2. Lets try on the audio signal.
Y1=flipud(y);
sound(Y1,Fs);
plot(t,Y1)

Figure 3: Reversed Audio Signal

Changing length of sound signal


To change the length of the sound signal we have to choose the required no of sample. For
example, to change the sound signal from 9 sec to 4 seconds length, we use the following

Y2=y((1:4*Fs),1);% see eqn (1) to understand this line


soundsc(Y2,Fs);
time=(1/Fs)*length(Y2);
t=linspace(0,time,length(Y2));
plot(t,Y2)

command

Department of Electrical Engineering, NUML, Islamabad


Figure 4. Clipped Signal of 10 Seconds

Digital Delay
Now let's add a delay to our sound sample. Below mentioned code will add 5 second delay to
signal.
Y3=[zeros(5*Fs,1); y];
soundsc(Y3,Fs);
time=(1/Fs)*length(Y3);
t=linspace(0,time,length(Y3));
plot(t,Y3)

Figure 5. Delayed Signal by 5 seconds

Department of Electrical Engineering, NUML, Islamabad


Echo
In audio signal processing and acoustics, echo is a reflection of sound that arrives at the listener
with a delay after the direct sound. Typical examples are the echo produced by the bottom of a
well, by a building, or by the walls of an enclosed room and an empty room. A simple analytical

model of an echo can be given by:


where the α(t) function attenuates the volume over time and T is the time delay introduced by
reflection. Range of α(t) will lie between (0, 1). This implies that the echo’s strength is weaker
than the true signal. And T ≥ 0, this implies that the echo always arrives at a time later than the
true signal (post-echo). So, the overall signal (r(t)) is formed by a simple addition of the original
signal and its echo:
r ( t )=s ( t ) + se (t)

This process is illustrated in the figure below for the simple case where α(t) is a const

Figure 6. Echo Model

delay = 4;
alpha = 0.3;
yw = [y;zeros(delay*Fs,1)];% to make signals of equal length, otherwise addition will
give error
se =[zeros(delay*Fs,1);(y* alpha)];
r = yw + se;
sound(r,Fs);
time=(1/Fs)*length(r);
t=linspace(0,time,length(r));
plot(t,r)
xlabel('time');
ylabel('Amplitude')

Department of Electrical Engineering, NUML, Islamabad


Figure 7. Echoed Output of our Audio Signal

Analysis
LAB WORKSHEET (Lab # 10)
1. Try sound operations using different sound signals.
Lab Assignment
Make a neat Lab Report.

Conclusion
Sound signals and different operations on sound signals has been studied and implemented in Matlab.

Department of Electrical Engineering, NUML, Islamabad


LAB 11: Study Laplace transform using Matlab.

Objective:-
The theme of this lab to perform the convolution for finding the output of an LTI system using
system’s impulse response and input signal. Second part of the lab comprises transfer function
representation and Laplace transformation.
Equipment required:-
 A computer
 MATLAB 15 or higher

THEORY:
Convolution Consider a discrete time system with input x[n] and output t[n]. Output y[n] is
computed output of the system through impulse response which is the output of the system when
the input is unit impulse. When Impulse response is given we can find out the system output by
following relation

For continuous signal, output is computed through following relation.

Convolution using MATLAB


To find out the output through convolution, firstly vector x[n] and h[n] are to be defined. Then the
output is computed through the following command

Command conv(x,h) assumes that the 1st element in x correspond to the n=0, 1st element in vector
h corresponds to n=0. SO the 1st element in yn will also correspond to n=0.
The command Conv () can also be used to multiply polynomials.
Suppose the coefficients of the polynomial a are given in vector A and that of b are given in B.
then coefficients of the output polynomial can be found out as:
For Example
a(s)=S+1
b(s)=S+2 %then

Department of Electrical Engineering, NUML, Islamabad


A=[1 1 ];
B=[1 2 ];
ab=conv(A,B)
%output comes out to be
ab=[1 3 2]
Example: Given the following input signal for discrete LTI system and impulse response.
x [n ]= [1,2,1,2,1,1]
h[n ]= [1,2, -1,1,3]
Code to find the convolved signal is given below.
x=[1,2,1,2,1,1];
h=[1,2,-1,1,3];
y=conv(x,h);
subplot(311);stem(x);title('Input Signal');
subplot(312);stem(h);title('Impulse Response');
subplot(313);stem(y);title('output Signal');

Department of Electrical Engineering, NUML, Islamabad


Laplace Transform
Laplace transform is used to transform a function/signal from time domain to s domain (complex
domain). System can be analyzed and performed different operations in S domain and then can be
taken back into t domain. Laplace transform converts the function expression into simple
algebraic polynomial. Following expression is used to calculate the Laplace transform of a time
domain function f(t).

In Matlab we solve the Laplace transform using symbolic math toolbox. Function used for finding
the Laplace is Laplace().
Example:
Let f(t)=t and we have to find the Laplace transform of the function. Matlab code for this is given
below.
syms t
f=t;
F=laplace(t)

Output returned is
F=1/S2
Example:
Laplace transform of e-at is calculated as:
Syms a t s
f=exp(-a*t);
F=laplace(f);

Output comes out to be


F=1/s+a
Inverse Laplace Transform
Laplace transform of any time domain function can be returned back to time domain by using
inverse Laplace transform. Following is the relation for the inverse laplace transform

In MATLAB we find out the inverse laplace transform using symbolic math toolbox. ilaplace is
function for finding the inverse laplace.
Example: Given below the transfer function
Department of Electrical Engineering, NUML, Islamabad
(S+ 3)
H(s)=
( S+1)(S +2)
Find the inverse laplace.
MATLAB Code is given below
Syms s
H=(s+3)/ ((s+1)*(s+2));
F=ilaplace (H);
Output comes out as:
F =2/exp(t) - 1/exp(2*t)
In finding the inverse Laplace often we encounter improper fractions having numerator power
greater than denominator. For such fractions we first divide the polynomials (numerator and
denominator) and then make partial fractions before taking inverse Laplace.
Example: Find the inverse Laplace of the following transfer function
3 2
S +3 S + 3
H(S)= 3 2
S + 8 S + S+ 5
In MATLAB we solve it as:
num=[1 3 0 3]; % Co-efficients of numerator
den=[1 8 15]; % co-efficients of denominator
[Q,R]=deconv(num,den);
% Divisions of two polynomials to make improper fraction a proper
fraction
[r,p,k]=residue(num,den);
%Partial fraction of the transfer function
%By residue we get the following parameters
r=

23.5000
1.5000
>> p
p=
-5
-3
>> k
k=
1 -5
From values above we write Matlab expression for h(s) as
Syms s
h=(s-5)+(23.5/(s+5))+(1.5/(s+3));
f=ilaplace(h);
Output comes out to be
f = dirac(1,t)-5*dirac(t)+47/2*exp(-5*t)+3/2*exp(-3*t)
Department of Electrical Engineering, NUML, Islamabad
Note:
1. Deconv returns the output as quotient (Q) and Remainder (R)
2. Residue converts the fraction to partial fraction and returns three vectors r (constants of
numerators), p (poles) and K (direct terms).
3. Dirac is the built-in function for unit impulse.

Analysis
LAB WORKSHEET (Lab # 11)
1. Find the output of the LTI system when x(n)= {1,1,2,1,1,3} and h(n)={1,2,-1,1} where
x(n) is from -3≤ n ≤2 and h(n) is from -1≤ n ≤2 .
2. Find the output when
x(t )=α t u(t)
h(t )= β t u(t)
where α =0.1
β=0.3
and -3≤ t ≤ 3

Lab Assignment
Make a neat Lab Report.
Conclusion
Laplace transform and inverse laplace transform has been studied and implemented in Matlab.

Department of Electrical Engineering, NUML, Islamabad


LAB 12: Implementation of GUI in Matlab.

Objective:-
Objective of the lab is to have basic interface of Matlab GUI, its usage and developing a user
desired GUI according to requirement.
Equipment required:-
 A computer
 MATLAB 15 or higher

THEORY:

GUI: Graphical User Interface


Graphical user interface is a graphical display in one or more windows containing
controls called components that enable a user to perform interactive tasks.
In Matlab, GUI provide a graphical environment in which user can create its own interactive
system. Functional approach in MATLAB GUI is component based. Components involve
different types of buttons, sliders, axes etc.
Accessing GUI in Matlab
Matlab has separate GUI environment that is called GUIDE (Graphical User Interface
development Environment). It provides a set of tools for creating graphical user interfaces
(GUIs). In Matlab command window type the following command
>>GUIde
You will get the following window open

The 1st option prompts you to open a blank GUI while below are some example GUIs available in
Matlab library.

Department of Electrical Engineering, NUML, Islamabad


Select Blank GUI from the window. You will get the following window open.

Window opened is called GUI Layout Editor. Left side of the window contains different types of
buttons. This area is called component palette. In order to show names of the components,
choose File>Preferences>Show names in component palette. Components will be shown with
their names.

Department of Electrical Engineering, NUML, Islamabad


Building a Simple GUI
Suppose we want to build a GUI which takes a frequency input from the user and plots sine wave
of that frequency.
Followings are the steps to create GUI.
Step1: Understanding the Problem/Requirement
For this GUI we need a user given frequency and in return a sine wave is to be generated. From
this we will layout our GUI
Step 2: Preparing a Draft for GUI.
Second prepare a draft our GUI as per requirement. We need a user given frequency and
in return a plot of sine wave. So we need something to take input from the user and a place to plot
the wave. In addition we may need an executer button which plots the wave or performs the
operation.
Step 3: Laying out GUI components
Second step is to layout your GUI as per draft.
a. For getting an input on run time, we use Edit Text and drag it in your layout editor.
b. For plotting we use Axes component so drag it in your layout editor.
c. Drag a Push Button and place it on editor, it will be used as executor.
d. In order to show some title for the GUI and input frequency , drag two static buttons and
place them in layout in the following manner.

Department of Electrical Engineering, NUML, Islamabad


Step 4: Setting Parameters
Next step is to set the parameters for each block. Choose View>Property Inspector.

Department of Electrical Engineering, NUML, Islamabad


A new window opens called Property Inspector as shown below.

Window contains two columns, 1st column contains the property name while 2nd contains
its value. We set the parameters one by one.
Push Button

Double click on the push button; its property inspector window will be opened.

Department of Electrical Engineering, NUML, Islamabad


 From the list, choose String property and edit its value from pushbutton to Plot sin(x). It will
be shown as visual name of the button.
 Now select Font and change its value to 20.
 Select color and choose use your own choice.
 Below the String there is a property called Tag, change its value to Plotter. Tag is the name
used for programming a function for GUI.

Edit Text
a. Set String Value to 0.
b. Font size to 15.
c. Color of your own choice
d. Set Tag to input_freq
Static Text1
a. Set String to Sine Wave Generator
b. Font size to 20
c. Color of your own choice
Static Text2
a. Set String to Enter Frequency
b. Set font size to 20
c. Color of your own choice
Now the GUI looks like below.

Department of Electrical Engineering, NUML, Islamabad


Step 5: Saving GUI
Save the GUI by singengui or any name. You will get two files upon saving.
1. Fig file
2. M file

Fig file
It is a binary file that contains all information of the blocks used in GUI and saves it as a
figure.

M file
When you save your GUI layout, GUIDE automatically generates a file of MATLAB
code for controlling the way the GUI works. This file contains code to initialize the GUI and
organizes the GUI callbacks.
Callbacks are functions that execute in response to user-generated events, such as a
mouse click. Using the MATLAB editor, you can add code to the callbacks to perform the
functions you want. You can also add new functions for callbacks to use.

Step 6: Programming GUI


As soon as you save it Matlab should generate the skeleton source code for you and the
source code should automatically open in an editor. Before Programming GUI followings are to
be kept in mind.

 GUI in Matlab in essence is a collection of objects. Each object has a unique handle
(name). During programming we access the particular object through its handle. Syntax to
access the object is handles. Tag e.g handles.edittext.
 All handles are stored in a structure named hObject.

Department of Electrical Engineering, NUML, Islamabad


 Name of each function for a block is the same as Tag name of the block in GUI.
 Objects used in GUI have input and output type of string.
 For getting an input in GUI from external, we use get() functions. Function is used as
get(H,’property name’)
 We setting a value as output we use set() function. Function is used as set(H,’property
name’,property value)

In our GUI we can define the flow of the GUI as getting the input from the user, generating a
sine wave and plotting it. All can be done if we program the push button which takes input,
generate sine wave and plot it.
Traverse through m file and choose plotter_callback or click the f() button on the main meu
which shows you the list of functions available in m file and select plotter_callback. It will take
you to the code of that function. This function is for push button as its Tag was set to plotter.
Add the following code below the function definition line under the comment lines.

freq=str2num(get(handles.input_freq,’string’));
x=0 :(2*pi)/100:2*pi;
y=sin(x*freq);
% accessing the axes block for plotting
axes(handles.axes1)
plot(y)

Since frequency is of numeric type so input from the user is converted to number and saved as
freq. Next we generate a sine wave of frequency with x number of points. To plot the sine wave
we access the axes through handles and plot the wave.
Step 7: Running GUI
Save the code and run the fig file. You will get following GUI

Department of Electrical Engineering, NUML, Islamabad


Enter your desired frequency and click the push button named Plot sin(x). you will see the
sine wave of frequency.

Department of Electrical Engineering, NUML, Islamabad


Analysis
LAB WORKSHEET (Lab # 12)
1. Build a Matlab GUI that performs the following operations.
a. Generation of square wave of given time period.
b. Generation of cosine wave of given frequency.

GUI should contain single interference for all operations which will be selected by the user.
Mention the code, output figures and properites of the blocks us

Lab Assignment
Make a neat Lab Report.

Conclusion
GUI has been studied and implemented in Matlab.

Department of Electrical Engineering, NUML, Islamabad


LAB 13: Exploration of Simulink Library in Matlab.

Objective:-
Objective of the lab is to have basic interface of Matlab GUI, its usage and developing a user
desired GUI according to requirement.
Equipment required:-
 A computer
 MATLAB 15 or higher

THEORY:


To begin your SIMULINK session open first MATLAB ICON by clicking
mouse twice and then type
»simulink
You will now see the Simulink block library.

Department of Electrical Engineering, NUML, Islamabad



Browse through block libraries. E.g., if you click Continuous, you will see the
following:

Department of Electrical Engineering, NUML, Islamabad



Math Operations library is shown below

Department of Electrical Engineering, NUML, Islamabad


Department of Electrical Engineering, NUML, Islamabad
After browsing through other block libraries, we are now ready to start generating a simple
Simulink diagram.
• Choose in menu selection File, then New and Model. This file will be called
untitled.

Untitled file, where the SIMULINK configuration is constructed using different


blocks in the library. With a mouse you can configure your model into the empty
space.

EXAMPLE 1: Input signal is sin t . It is fed into an amplifier with gain 2. Simulate the
output of the amplifier.
Solution: Pick firs the amplifier. This you can find under Math and it is called Gain. Move
the cursor on top of Gain, keep it down and move the Gain block to untitled file and
release it. If you fail, try again. The result is shown below.
Department of Electrical Engineering, NUML, Islamabad
The gain has only one parameter, which has value of 1. You can change it by moving the
cursor close to 1 and clicking once and then operating as you would with any word
processing system. Once finished, click OK. The numerical value inside the block will
now change to 2. Next find the input signal block. This is under Sources and is called
Sine Wave. Again move the cursor on top of it, keep pressing the mouse while you move
the block to the untitled file and then release the mouse. In order to see the result, you
need to install a sink from Sinks library. In the beginning, the easiest sink to use is scope.
Move that block in the same way as the others to the untitled file. The result is shown
below.

Department of Electrical Engineering, NUML, Islamabad


The only thing missing of the system is to connect the peaces together. This is done with
the mouse. Take the cursor to the output of Sine Wave block. You’ll see a hairline cursor,
when you are close enough. Now press the mouse down. Keep it down and move it close
to the input of gain. You’ll see a line forming, while you drag your mouse. Once you reach
the input another hairline cursor can be seen and you can release the mouse.

Department of Electrical Engineering, NUML, Islamabad


Your simulation system is now complete. Before simulation you should check that the
parameter values in the Sine Wave block are correct. Open it by placing the cursor on top
and click twice.

For this example Amplitude is 1 and frequency (rad/s) is also 1, so default values are
OK. There is no phase shift and sampling is not issue here.
Department of Electrical Engineering, NUML, Islamabad
You can begin simulation by choosing Start simulation from Simulation menu or by
clicking the start button.
Simulation menu

Start button

Department of Electrical Engineering, NUML, Islamabad


Department of Electrical Engineering, NUML, Islamabad
The solution is found by choosing under Simulation menu Start simulation or by
clicking Start button.

The result is shown above. If you study the equation and the result, it is clear (why?) that
we have made a mistake in configuration. The sign in summation is wrong. Correct it as
shown below. Now the result corresponds to our expectations (if any).

Department of Electrical Engineering, NUML, Islamabad


If you want to see both the input and output at the same time, use Mux (multiplexer) block,
which you can find under Signals and Systems block library. Set up the system as shown
below.

MATLAB Command window

Department of Electrical Engineering, NUML, Islamabad


Once you have defined your system in SIMULINK window, you can simulate also on the
MATLAB Command window. Save your model – currently it has the name Untitled, so use
that. Go to MATLAB command window and type » help sim. The following lines will help
you to understand how to simulate.

» help sim

SIM Simulate a Simulink model


SIM('model') will simulate your Simulink model using all simulation
parameter dialog settings including Workspace I/O options.

The SIM command also takes the following parameters. By default


time, state, and output are saved to the specified left hand side
arguments unless OPTIONS overrides this. If there are no left hand side
arguments, then the simulation parameters dialog Workspace I/O settings are
used to specify what data to log.

[T,X,Y] = SIM('model',TIMESPAN,OPTIONS,UT)
[T,X,Y1,...,Yn] = SIM('model',TIMESPAN,OPTIONS,UT)

T : Returned time vector.


X : Returned state in matrix or structure format.
The state matrix contains continuous states followed by
discrete states.
Y : Returned output in matrix or structure format.
For block diagram models this contains all root-level
outport blocks.
Y1,...,Yn : Can only be specified for block diagram models, where n
must be the number of root-level outport blocks. Each outport
will be returned in the Y1,...,Yn variables.

'model' : Name of a block diagram model.


TIMESPAN : One of:
TFinal,
[TStart TFinal], or
[TStart OutputTimes TFinal].
OutputTimes are time points which will be returned in T,
but in general T will include additional time points.
OPTIONS : Optional simulation parameters. This is a structure
created with SIMSET using name value pairs.
UT : Optional extern input. UT = [T, U1, ... Un]
where T = [t1, ..., tm]' or UT is a string containing a
function u=UT(t) evaluated at each time step. For table
inputs, the input to the model is interpolated from UT.

Specifying any right hand side argument to SIM as the empty matrix, [],
will cause the default for the argument to be used.

Only the first parameter is required. All defaults will be taken from the block
diagram, including unspecified options. Any optional arguments specified will
override the settings in the block diagram.
See also SLDEBUG, SIMSET.

Overloaded methods
help network/sim.m

The simplest way to start is to use sim command in the following way.

» [t,x,y]=sim('untitled');

Next you can use plot command to see the result.


» plot(t,x)

To see y, you need to introduce an output in the SIMULINK model. Check below.

Another issue that we have not considered is initial condition. As you know every differential
equation should have initial conditions given. The default value in SIMULINK is zero. To
change that click the integrator. You’ll see the following display.

Department of Electrical Engineering, NUML, Islamabad


Double-
click

Initial condition

As seen above you can change the initial value to e.g. –3.

The default time for simulation is 10. If you wish to simulate longer you have to
change it. To do that open Simulation menu and choose Simulation parameters.

You can change the Stop time according to your needs.

Complete the exercise. Run the simulation from SIMULINK and also from Command
window.

Department of Electrical Engineering, NUML, Islamabad


Analysis
LAB WORKSHEET (Lab # 13)
1. Explore different logical and math operations of simulink library.
Lab Assignment
Make a neat Lab Report.
Conclusion
Simulink blocks has been studied and implemented in Matlab.

Department of Electrical Engineering, NUML, Islamabad


LAB 14: Study and implementation of spectral analysis in Matlab.

Objective:-
The theme of this lab to perform the different frequency transformation to study spectrum of
different frequencies.
Equipment required:-
 A computer
 MATLAB 15 or higher

THEORY:
1. Spectral analysis using Fourier transform

%generate a complex signal


fs=10000; %sampling rate
t=0:1/fs:0.1; %sampling instants
x=sin(2*pi*1500*t)+sin(2*pi*4000*t); %two sinusoids
%
%perform 1000-point transform
y=fft(x,1000); %y contains 1000 complex amplitudes
y=y(1:500); %just look at first half
m=abs(y); %magnitude of sinusoids
p=unwrap(angle(y)); %phase of sinusoids, unwrap()
%copes with 360 degree jump
%plot spectrum 0...fs/2
f=(0:499)*fs/1000;
subplot(2,1,1)
plot(f,m);
ylabel('ABS. Magnitude');
grid on;
subplot(2,1,2)
plot(f,p*180/pi);
ylabel('phase [degrees]');
xlabel('Frequency [Hertz]');

Department of Electrical Engineering, NUML, Islamabad


Y=fft(x,1024);
magnitude=abs(Y);
powerdB=20*log10(magnitude+eps);

Y=fft(x1,1024); %waveform-> spectrum


%process Y in some way

Department of Electrical Engineering, NUML, Islamabad


x2=real(ifft(Y));
2. Windowing a signal

%divide up a signal in to windows


x=sin(2*pi*500*(1:10000)/10000); %example signal
nx=length(x); %size of signal
w=hamming(32)'; %hamming window
nw=length(w); %size of window
pos=1;
while(pos+nw<=nx) %while enough signal left
y=x(pos:pos+nw-1).*w; %make window y
%process window y
pos=pos+nw/2;
end

Analysis
LAB WORKSHEET (Lab # 14)
1. Generate two different sinusoids of different frequencies adding them together
and see results.
Lab Assignment
Make a neat Lab Report.

Conclusion
Frequency transformation has been studied and implemented in Matlab.

Department of Electrical Engineering, NUML, Islamabad

You might also like