Professional Documents
Culture Documents
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.
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.
LAB OUTLINE
Week No. Signals and Systems Lab
Introduction to MATLAB and basic commands.
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
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.
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
logical magic(4) > 10 Array of logical values of 1 or 0 to represent true and false
respectively. Two-dimensional arrays can be sparse.
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.
(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:
>> 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>
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
+ Addition
- Subtraction
* Multiplication
/ Division
\ Left division (described in "Matrices and Linear Algebra" in the MATLAB documentation)
^ Power
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.
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
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
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
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:
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.
[ ]
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
Lab Assignment
Make a neat Lab report.
Conclusion
In this Lab we study the implementation and use of basic operations in Matlab.
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.
Command-Window
>> x=[1 2 3 4 5 6];
>> ave=average(x)
ave =
3.5000
c. Flow Control
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.)
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:
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 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)
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)
syms x
f = sin(5*x)
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)
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)
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:
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.
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:
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');
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');
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
Let x (t)= {
2 ,|t|≤ 1
0 ,|t|>1
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
{
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.
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
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.
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 )}
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');
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');
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).
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');
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.
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
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.
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.
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.
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.
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)
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.
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
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)
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.
{
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);
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.
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
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.
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.
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.
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
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.
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.
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.
2
t
3
a o=
2
a n=0
{
0 ,∧n=even
b n= 6
,∧n=odd
πn
MATLAB IMPLEMENTATION
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.
Q3: Generate square wave using below equation for following number of harmonics
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)
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
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
Example
Find the DTFT for the following discrete time signal
_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.
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
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.
t= Time delay/2
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.
% plotting
t=linspace(0,time,length(Y));
plot(t,Y)
% Reading Audio File:
load handel
sound(y,Fs);
% Calculating Total Time of Signal
% 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.
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)
command
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)
This process is illustrated in the figure below for the simple case where α(t) is a const
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')
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.
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
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
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);
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.
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:
The 1st option prompts you to open a blank GUI while below are some example GUIs available in
Matlab library.
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.
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.
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.
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.
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.
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
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.
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.
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.
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
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).
» help sim
[T,X,Y] = SIM('model',TIMESPAN,OPTIONS,UT)
[T,X,Y1,...,Yn] = SIM('model',TIMESPAN,OPTIONS,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');
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.
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.
Complete the exercise. Run the simulation from SIMULINK and also from Command
window.
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
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.