Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

Index

S. No. Experiment Date Page Remark


1 Introduction to MATLAB
2 Generation of various signal and
sequences
3 Convolution of Discrete Signal

4 Correlation of Discrete Signal


5 Circular Convolution of Discrete Signal

2
3
INTRODUCTION TO MATLAB

MATLAB (MATRIX LABORATORY):

MATLAB is a software package for high-performance language for technical


computing. It integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in familiar mathematical
notation. Typical uses include the following

➢ Math and computation


➢ Algorithm development
➢ Data acquisition
➢ Modeling, simulation, and prototyping
➢ Data analysis, exploration, and visualization
➢ Scientific and engineering graphics
➢ Application development, including graphical user interface building

The name MATLAB stands for matrix laboratory. MATLAB was originally written
to provide easy access to matrix software developed by the LINPACK and EISPACK
projects. Today, MATLAB engines incorporate the LAPACK and BLAS libraries,
embedding the state of the art in software for matrix computation.

MATLAB has evolved over a period of years with input from many users. In
university environments, it is the standard instructional tool for introductory and advanced
courses in mathematics, engineering, and science. In industry, MATLAB is the tool of
choice for high-productivity research, development, and analysis.

MATLAB features a family of add-on application-specific solutions called toolboxes.


Very important to most users of MATLAB, toolboxes allow learning and applying
specialized technology. Toolboxes are comprehensive collections of MATLAB functions
(M-files) that extend the MATLAB environment to solve particular classes of problems.
Areas in which toolboxes are available include Image processing, signal processing,
control systems, neural networks, fuzzy logic, wavelets, simulation, and many others. The
main features of MATLAB
1. Advance algorithm for high performance numerical computation ,especially in the
Field matrix algebra

4
2. A large collection of predefined mathematical functions and the ability to define
one’s own functions.
3. Two-and three dimensional graphics for plotting and displaying data
4. A complete online help system
5. Powerful, matrix or vector oriented high level programming language for individual
applications.
6. Toolboxes available for solving advanced problems in several application areas

The tutorials are independent of the rest of the document. The primarily objective is
to help you learn quickly the first steps. The emphasis here is “learning by doing”.
Therefore, the best way to learn is by trying it yourself. Working through the examples will
give you a feel for the way that MATLAB operates. In this introduction we will describe
how MATLAB handles simple numerical expressions and mathematical formulas.
The name MATLAB stands for Matrix Laboratory. MATLAB was written
originally to provide easy access to matrix software developed by the LINPACK (linear
system package) and EISPACK (Eigen system package) projects.
MATLAB [1] is a high-performance language for technical computing. It integrates
computation, visualization and programming environment. Furthermore, MATLAB is a
modern programming language environment: it has sophisticated
data structures contains built-in editing and debugging tools , and supports object-oriented
programming These factors make MATLAB an excellent tool for teaching and research.
MATLAB has many advantages compared to conventional computer languages (e.g.,
C, FORTRAN) for solving technical problems. MATLAB is an interactive system whose
basic data element is an array that does not require dimensioning. The software package
has been commercially available since 1984 and is now considered as a standard tool at
most universities and industries worldwide.
It has powerful built-in routines that enable a very wide variety of computations. It
also has easy to use graphics commands that make the visualization of results immediately
available. Specific applications are collected in packages referred to as toolbox. There are
toolboxes for signal processing, symbolic computation, control theory, simulation,
optimization, and several other fields of applied science and engineering.
Basic features
As we mentioned earlier, the following tutorial lessons are designed to get you started
quickly in MATLAB. The lessons are intended to make you familiar with the basics of

5
We urge you to complete the exercises given at the end of each lesson.
A minimum MATLAB session
The goal of this minimum session (also called starting and exiting sessions) is to learn the
first steps:
• How to log on
• Invoke MATLAB
• Do a few simple calculations
• How to quit MATLAB
Starting MATLAB
After logging into your account, you can enter MATLAB by double-clicking on the
MATLAB shortcut icon (MATLAB 7.0.4) on your Windows desktop. When you start
MATLAB, a special window called the MATLAB desktop appears. The desktop is
a window that contains other windows. The major tools within or accessible from the
desktop are:
• The Command Window
• The Command History
• The Workspace
• The Current Directory
• The Help Browser
• The Start button

Figure 1.1: The graphical interface to the MATLAB workspace

6
When MATLAB is started for the first time, the screen looks like the one that shown in
the Figure 1.1. This illustration also shows the default configuration of the MATLAB desktop.
You can customize the arrangement of tools and documents to suit your needs.
Now, we are interested in doing some simple calculations. We will assume that
you have sufficient understanding of your computer under which MATLAB is being run.
You are now faced with the MATLAB desktop on your computer, which contains the
prompt (>>) in the Command Window. Usually, there are 2 types of prompt:
Using MATLAB as a calculator
As an example of a simple interactive calculation, just type the expression you want
to evaluate. Let’s start at the very beginning. For example, let’s suppose you want to
calculate the expression, 1 + 2 × 3. You type it at the prompt command (>>) as follows,
>> 1+2*3
ans = 7
You will have noticed that if you do not specify an output variable, MATLAB uses a
default variable ans, short for answer, to store the results of the current calculation. Note
that the variable ans is created (or overwritten, if it is already existed). To avoid this, you
may assign a value to a variable or output argument name. For example
>> x = 1+2*3
x =7
will result in x being given the value 1 + 2*3=7. This variable name can always be used to
refer to the results of the previous computations. Therefore, computing 4 result in >> 4*x

ans =28.0000
Before we conclude this minimum session, Table 1.1 gives the partial list of arithmetic
Operators.
Basic arithmetic operators
Symbol Operation Example
+ Addition 2+3
- Subtraction 2-3
*Multiplication 2*3
/ Division 2/3

3. Quitting MATLAB
To end your MATLAB session, type quit in the Command Window, or select
File MATLAB in the desktop main menu.
Getting started

7
After learning the minimum MATLAB session, we will now learn to use some additional
operations.
1 Creating MATLAB variables
MATLAB variables are created with an assignment statement. The syntax of variable
assignment is
variable name = a value (or an expression)
For example,
>> x = expression
Where expression is a combination of numerical values, mathematical operators,
variables, and function calls. On other words, expression can involve:
• manual entry
• built-in functions
• user-defined functions
Overwriting variable
Once a variable has been created, it can be reassigned. In addition, if you do not
wish to see the intermediate results, you can suppress the numerical output by putting a
semicolon (;) at the end of the line. Then the sequence of commands looks like this:
>> t = 5;>> t =
t+1 t =6
Error messages
If we enter an expression incorrectly, MATLAB will return an error message. For
example, in the following, we left out the multiplication sign, *, in the following expression
>> x = 10;
>> 5x
??? 5x
Error: Unexpected MATLAB expression
Making corrections
To make corrections, we can, of course retype the expressions. But if the expression is
lengthy, we make more mistakes by typing a second time. A previously typed command
can be recalled with the up-arrow key When the command is displayed at the command
prompt, it can be modified if needed and executed.
Controlling the hierarchy of operations or precedence
Let’s consider the previous arithmetic operation, but now we will
include example, 1 + 2×3 will become (1 + 2) ×3 >> (1+2)*3

8
ans =9
and, from previous example
>> 1+2*3
ans =7
By adding parentheses, these two expressions give di erent results: 9 and 7 The
order in which MATLAB performs arithmetic operations is exactly that taught in high
school algebra courses Exponentiations are done first , followed by multiplications and
divisions, and finally by additions and subtractions. However, the standard order of
precedence of arithmetic operations can be changed by inserting parentheses. For example,
the result of 1 +2×3 is quite deferent than the similar expression with parentheses (1+2) ×3.
The results are 7 and 9 respectively. Parentheses can always be used to overrule priority
and their use is recommended in some complex expressions to avoid ambiguity.
Therefore, to make the evaluation of expressions unambiguous, MATLAB has
established a series of rules. The order in which the arithmetic operations are evaluated is
given in Table 1.2. MATLAB arithmetic operators obey the same precedence rules as those
in Hierarchy of arithmetic operations Precedence Mathematical operations. The contents of
all parentheses are evaluated first, starting from the innermost parentheses and working
outward Second All exponentials are evaluated, working from left to right Third All
multiplications and divisions are evaluated, working from left to right Fourth All additions
and subtractions are evaluated, starting from left to right most computer programs. For
operators of equal precedence, evaluation is from left to right Now, consider another
example:
>> 1/(2+3^2)+4/5*6/7
ans =0.7766. or, if parentheses are missing,
>> 1/2+3^2+4/5*6/7
ans =10.1857.
So here what we get: two different results. Therefore, we want to emphasize the
importance of precedence rule in order to avoid ambiguity
Controlling the appearance of floating point number
MATLAB by default displays only 4 decimals in the result of the calculations, for example
-163. 6667, as shown in above examples. However, MATLAB does numerical calculations
in double precision, which is 15 digits. The command format controls how the results of
computations are displayed. Here are some examples of the different formats together with
the resulting outputs
>> format short

9
>> x=-163.6667
If we want to see all 15 digits, we use the command format long
>> format long
>> x= -1.636666666666667e+002
To return to the standard format, enter format short, or simply format There are
several other formats. For more details, see the MATLAB documentation, or type help
format Note - Up to now, we have let MATLAB repeat everything that we enter at the
prompt (>>). Sometimes this is not quite useful, in particular when the output is pages en
length. To prevent MATLAB from echoing what we type, simply enter a semicolon (;) at
the end of the command. For example,
>> x=-163.6667;
and then ask about the value of x by typing,
>> x
x =-163.6667
Managing the workspace
The contents of the workspace persist between the executions of separate
commands. There- fore, it is possible for the results of one problem to have anent on the
next one. To avoid this possibility, it is a good idea to issue a clear command at the start of
each new independent calculation
>> clear
The command clear or clear all removes all variables from the workspace. This frees up
system memory. In order to display a list of the variables currently in the memory type
>> who
While, whos will give more details which include size, space allocation, and class
of the variables
Keeping track of your work session
It is possible to keep track of everything done during a MATLAB session with the
diary command.
>> diary
or give a name to a created file
>> diary FileName
where FileName could be any arbitrary name you choose, The function diary is useful if you
want to save a complete MATLAB session. They save all input and output as they appear in
the MATLAB window. When you want to stop the recording, enter diary off. If you want to
start recording again, enter diary on. The file that is created is a simple text file.

10
It can be opened by an editor or a word processing program and edited to remove
extraneous material, or to add your comments. You can use the function type to view the
diary file or you can edit in a text editor or print. This command is useful, for example in
the process of preparing a homework or lab submission.
Entering multiple statements per line
It is possible to enter multiple statements per line. Use commas (,) or semicolons (;)
to enter more than one statement at once. Commas (,) allow multiple statements per line
Without suppressing output
>> a=7; b=cos (a), c=cosh
(a) b =0.6570
c =548.3170
Miscellaneous commands
Here are few additional useful commands:
• To clear the Command Window, type clc
• To abort a MATLAB computation, type ctrl-c
• To continue a line, type . . .
Getting help
To view the online documentation, select MATLAB Help from Help menu or
MATLAB Help directly in the Command Window. The preferred method is to use the
Help Browser. The Help Browser can be started by selecting the? icon from the desktop
toolbar. On the other hand, information about any command is available by typing >> help
Command
Another way to get help is to use the look for command. The help command searches for
an exact function name match, while the look for command searches the quick summary
information in each function for a match. For example, suppose that we were looking for a
function to take the inverse of a matrix. Since MATLAB does not have a function named
inverse, the command help inverse will produce nothing. On the other hand, the command
look for inverse will produce detailed information, which includes the function of interest,
inv
>> look for inverse
Note - At this particular time of our study, it is important to emphasize one main point.
Because MATLAB is a huge program; it is impossible to cover al l the details of each
function one by one. However, we will give you information how to get help. Here are
some examples
• Use on-line help to request info on a specific function

11
>> help sqrt
• In the current version (MATLAB version 7), the doc function opens the on-line version
of the help manual. This is very helpful for more complex commands
>> doc plot
• Use look for to find functions by keywords. The general form is
>> look for Function Name

PROCEDURE:-
• Open MATLAB
• Open new M-file
• Type the program
• Save in current directory
• Compile and Run the program
• For the output see command window\ Figure window

12
BASIC OPERATIONS ON MATRICES

Aim: To generate matrix and perform basic operation on matrices using MATLAB
Software.
EQUIPMENT:
• PC with operating system
• MATLAB Software

THEORY:
MATLAB treats all variables as matrices. For our purposes a matrix can be thought of
as an array, in fact, that is how it is stored.
• Vectors are special forms of matrices and contain only
one row OR one column.
• Scalars are matrices with only one row AND one column. A matrix with only one
row AND one column is a scalar. A scalar can be rebated in MATLAB as follows:
» a_value=23
a_value =
• A matrix with only one row is called a row vector. A row vector can be created in
MATLAB as follows :
» rowvec = [12 , 14 , 63]
rowvec =
12 14 63
• A matrix with only one column is called a column vector. A column vector can be
created in MATLAB as follows:
» colvec = [13 ; 45 ; -2]
colvec =
13
45
-2
• A matrix can be created in MATLAB as follows:
» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]
matrix =
123
456
789

A portion of a matrix can be extracted and stored in a smaller matrix by specifying the
names of both matrices and the rows and columns to extract. The syntax is:
sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;
Where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the
beginning and ending columns to be extracted to make the new matrix.

13
• A column vector can be extracted from a matrix.
• As an example we create a matrix below:
» matrix=[1,2,3;4,5,6;7,8,9]
matrix =
123
456
789

Here we extract column 2 of the matrix and make a column vector:


» col_two=matrix( : ,
2) col_two =
258
• A row vector can be extracted from a matrix.
As an example we create a matrix below:
» matrix=[1,2,3;4,5,6;7,8,9]
matrix =
123
456
789
• Here we extract row 2 of the matrix and make a row vector. Note that the
2:2 specifies the second row and the 1:3 specifies which columns of the row.
» rowvec=matrix(2 : 2 , 1 :3)
rowvec =4 5 6
» a=3;
» b=[1, 2, 3;4, 5,
6] b =
123
456
» c= b+a % Add a to each element of b
c=
456
789
• Scalar - Matrix Subtraction
» a=3;
» b=[1, 2, 3;4, 5, 6]
b =
123
456
» c = b - a %Subtract a from each element of b
c=
-2-10
123

• Scalar - Matrix Multiplication


» a=3;
» b=[1, 2, 3; 4, 5, 6]
b =
123
456
» c = a * b % Multiply each element of b by a
c=

14
369
12 15 18
• Scalar - Matrix Division
» a=3;
» b=[1, 2, 3; 4, 5, 6]
b =
123
456
» c = b / a % Divide each element of b by a
c=
0.3333 0.6667 1.0000
1.3333 1.6667 2.0000
a = [1 2 3 4 6 4 3 4 5]

a=

1 2 3 4 6 4 3 4 5

b=a+2
b=

3 4 5 6 8 6 5 6 7

A=[120;25-1;410-1]
A=

1 2 0

2 5 -1

4 10 -1

B=A'

B=

1 2 4

2 5 10
0 -1 -1

C=A*B

C=

5 12 24

12 30 59
24 59 117

Instead of doing a matrix multiply, we can multiply the corresponding elements of


two matrices or vectors using the .* operator.

15
C=A.*B

C=

1 4 0

4 25 -10
0 -10 1

Let's find the inverse of a matrix …

X = inv(A)
X=

5 2 -2

-2 -1 1
0 -2 1

and then illustrate the fact that a matrix times its inverse is the identity matrix.

I = inv(A) * A
I=

1 0 0

0 1 0
0 0 1

to obtain eigenvalues

eig(A)
ans =

3.7321

0.2679

1.0000

as the singular value decomposition.

svd(A)
ans =

12.3171

0.5149

16
0.1577
'

3. perform following operations on any two matrices

A+B
A-B
A*B
A.*B
A/B

4. Enter the following matrix at the command window and perform the following
A=[3451
5672

7893]
i. All the elements of all rows but first column
ii. All the elements of first row but all columns

iii. Element in second row and third column


iv. Reshape this matrix to (4×3) matrix
v. Determine inverse , Determinant ,rank, size, transpose, eigen values, of A
vii. Multiply A with another Matrix B
viii. perform arry multiplication of A and B
5. x= [2 3 4] ; y=[2 5 1] perform all logical operations (AND, OR, NOT, EXOR)
6. Perform following operations on any two matrices
A+B, A-B, A*B, A.*B, A/B, A./B, A^B, A.^B, A',A

17
PROGRAM:-
clc;
close all;
clear all;
a=[1 2 -9 ; 2 -1 2; 3 -4 3];
b=[1 2 3; 4 5 6; 7 8 9];
disp('The matrix a= ');a
disp('The matrix b= ');b % to find sum of a and b
c=a+b;
disp('The sum of a and b is ');c % to find difference of a and
b d=a-b;
disp('The difference of a and b is ');d %to find multiplication of a and
b e=a*b;
disp('The product of a and b is ');e % to find element-by-element multiplication

RESULT:-
Finding addition, subtraction, multiplication using Matlab was
Successfully completed

OUTPUT:-
The matrix a=
a=
1 2 -9
2 -1 2
3 -4 3
The matrix b=
b=
1 2 3
4 5 6
7 8 9

The sum of a and b is


c=
24-6
648
10412

The difference of a and b is


d=
0 0 -12
-2 -6 -4
-4 -12 -6

The product of a and b is


e=
-54 -60 -66
12 15 18
8 10 12

18
Experiment No: 2
GENERATION OF VARIOUS SIGNALS AND SEQUENCES
(PERIODIC AND APERIODIC), SUCH AS UNIT IMPULSE, UNIT
STEP, RAMP, SQUARE, SAWTOOTH, TRIANGULAR,
SINUSOIDAL, SINC)

Aim: To generate different types of signals Using MATLAB Software.


EQUIPMENTS:
• PC with operating system
• MATLAB Software

THEORY :

UNIT IMPULSE: a) Continous signal: 0 t 0


(t) = t=0
And
(t)dt = 1

Also called unit impulse function. The value of delta function can also be
defined in the sense of generalized function

(t) : Test Function


n=
b) Unit Sample sequence: δ(n)={ 1, 0
n≠
0, 0
i.e.

Matlab program:

%unit impulse generation


clc
close all

19
n1=-3;
n2=4;
n0=0;
n=[n1:n2];
x=[(n-n0)==0]
stem(n,x)

2) Unit Step Function u (t):

1 t 0
u(t) =
0 t 0

b) Unit Step Sequence u(n): )= { 1, n≥0


0, n<0

% unit step generation


n1=-4;
n2=5;
n0=0;
[y,n]=stepseq(n0,n1,n2);
stem(n,y);
xlabel('n')
ylabel('amplitude');
title('unit step');

20
Square waves: Like sine waves, square waves are described in terms of period,
frequency and amplitude:

Peak amplitude, Vp , and peak-to-peak amplitude, Vpp , are measured as you might
expect. However, the rms amplitude, Vrms , is greater than that of a sine wave. Remember
that the rms amplitude is the DC voltage which will deliver the same power as the signal. If
a square wave supply is connected across a lamp, the current flows first one way and then
the other. The current switches direction but its magnitude remains the same. In other
words, the square wave delivers its maximum power throughout the cycle so that Vrms is
equal to Vp . (If this is confusing, don't worry, the rms amplitude of a square wave is not
something you need to think about very often.)

Although a square wave may change very rapidly from its minimum to maximum
voltage, this change cannot be instaneous. The rise time of the signal is defined as the time
taken for the voltage to change from 10% to 90% of its maximum value. Rise times are
usually very short, with durations measured in nanoseconds (1 ns = 10-9 s), or
microseconds (1 µs = 10-6 s), as indicated in the graph

% square wave wave generator


fs = 1000;
t = 0:1/fs:1.5;
x1 = sawtooth(2*pi*50*t);
x2 = square(2*pi*50*t);

21
subplot(2,2,1),plot(t,x1), axis([0 0.2 -1.2 1.2])
xlabel('Time (sec)');ylabel('Amplitude'); title('Sawtooth Periodic Wave')
subplot(2,2,2),plot(t,x2), axis([0 0.2 -1.2 1.2])
xlabel('Time (sec)');ylabel('Amplitude'); title('Square Periodic Wave');
subplot(2,2,3),stem(t,x2), axis([0 0.1 -1.2 1.2]) xlabel('Time
(sec)');ylabel('Amplitude');

SAW TOOTH:
The sawtooth wave (or saw wave) is a kind of non-sinusoidal waveform. It is named
a sawtooth based on its resemblance to the teeth on the blade of a saw. The convention is
that a sawtooth wave ramps upward and then sharply drops. However, there are also
sawtooth waves in which the wave ramps downward and then sharply rises. The latter type
of sawtooth wave is called a 'reverse sawtooth wave' or 'inverse sawtooth wave'. As audio
signals, the two orientations of sawtooth wave sound identical. The piecewise linear
function based on the floor function of time t, is an example of a sawtooth wave with
period 1.

This sawtooth function has the same phase as the sine function. A sawtooth wave's
sound is harsh and clear and its spectrum contains both even and odd harmonics of the
fundamental frequency. Because it contains all the integer harmonics, it is one of the best
waveforms to use for synthesizing musical sounds, particularly bowed string instruments
like violins and cellos, using subtractive synthesis.

Applications

The sawtooth and square waves are the most common starting points used to create
sounds with subtractive analog and virtual analog music synthesizers. The sawtooth wave
is the form of the vertical and horizontal deflection signals used to generate a raster on

22
CRT-based television or monitor screens. Oscilloscopes also use a sawtooth wave for their
horizontal deflection, though they typically use electrostatic deflection.

On the wave's "ramp", the magnetic field produced by the deflection yoke drags the
electron beam across the face of the CRT, creating a scan line.

On the wave's "cliff", the magnetic field suddenly collapses, causing the electron
beam to return to its resting position as quickly as possible.

The voltage applied to the deflection yoke is adjusted by various means


(transformers, capacitors, center-tapped windings) so that the half-way voltage on the
sawtooth's cliff is at the zero mark, meaning that a negative voltage will cause deflection in
one direction, and a positive voltage deflection in the other; thus, a center-mounted
deflection yoke can use the whole screen area to depict a trace. Frequency is 15.734 kHz
on NTSC, 15.625 kHz for PAL and SECAM)

% sawtooth wave generator


fs = 10000;
t = 0:1/fs:1.5;
x = sawtooth(2*pi*50*t);
subplot(1,2,1);
plot(t,x), axis([0 0.2 -1 1]);
xlabel('t'),ylabel('x(t)')
title('sawtooth signal');
N=2; fs = 500;n = 0:1/fs:2;
x = sawtooth(2*pi*50*n);
subplot(1,2,2); stem(n,x),
axis([0 0.2 -1 1]);
xlabel('n'),ylabel('x(n)')
title('sawtooth sequence');

23
Triangular wave

A triangle wave is a non-sinusoidal waveform named for its triangular shape. A


band limited triangle wave pictured in the time domain (top) and frequency domain
(bottom). The fundamental is at 220 Hz (A2).Like a square wave, the triangle wave
contains only odd harmonics. However, the higher harmonics roll off much faster than in a
square wave (proportional to the inverse square of the harmonic number as opposed to just
the inverse).It is possible to approximate a triangle wave with additive synthesis by adding
odd harmonics of the fundamental, multiplying every (4n−1)th harmonic by −1 (or
changing its phase by π), and rolling off the harmonics by the inverse square of their
relative frequency to the fundamental. This infinite Fourier series converges to the triangle
wave:

%To generate a triangular pulse


A=2;
t = 0:0.0005:1;
x=A*sawtooth(2*pi*5*t,0.25); %5 Hertz wave with duty cycle 25%
plot(t,x);
grid;
axis([0 1 -3 3]);

24
%%To generate a triangular pulse
fs = 10000;t = -1:1/fs:1;
x1 = tripuls(t,20e-3);
x2 = rectpuls(t,20e-3);
subplot(211),plot(t,x1), axis([-0.1 0.1 -0.2 1.2])
xlabel('Time (sec)');
ylabel('Amplitude');
title('Triangular Aperiodic Pulse')
subplot(212),plot(t,x2), axis([-0.1 0.1 -0.2 1.2])
xlabel('Time (sec)');
ylabel('Amplitude');
title('Rectangular Aperiodic Pulse')
set(gcf,'Color',[1 1 1]),

25
%%To generate a rectangular pulse
t=-5:0.01:5;
pulse = rectpuls(t,2); %pulse of width 2 time units
plot(t,pulse)
axis([-5 5 -1 2]);
grid

Sinusoidal Signal Generation

The sine wave or sinusoid is a mathematical function that describes a smooth repetitive
oscillation. It occurs often in pure mathematics, as well as physics, signal processing,
electrical engineering and many other fields. Its most basic form as a function of time (t) is:

where:

• A, the amplitude, is the peak deviation of the function from its center position.
• ω, the angular frequency, specifies how many oscillations occur in a unit time
interval, in radians per second
• φ, the phase, specifies where in its cycle the oscillation begins at t = 0.

A sampled sinusoid may be written as:

26
where f is the signal frequency, fs is the sampling frequency, θ is the phase and A is the
amplitude of the signal. The program and its output is shown below:

Note that there are 64 samples with sampling frequency of 8000Hz or sampling time
of 0.125 mS (i.e. 1/8000). Hence the record length of the signal is 64x0.125=8mS.
There are exactly 8 cycles of sinewave, indicating that the period of one cycle is 1mS
which means that the signal frequency is 1KHz.

% sinusoidal signal
N=64; % Define Number of samples n=0:N-1; %
Define vector n=0,1,2,3,...62,63 f=1000; % Define
the frequency fs=8000; % Define the sampling
frequency x=sin(2*pi*(f/fs)*n); % Generate x(t)
plot(n,x); % Plot x(t) vs. t

title('Sinewave [f=1KHz, fs=8KHz]');


xlabel('Sample Number');
ylabel('Amplitude');

27
% Ramp
clc
close all
n=input('enter the length of
ramp'); t=0:n;
stem(t);
xlabel('t');
ylabel('amplitude');
title ('ramp')

SINC FUNCTION:
The sinc function computes the mathematical sinc function for an input vector or
matrix x. Viewed as a function of time, or space, the sinc function is the inverse Fourier
transform of the rectangular pulse in frequency centered at zero of width 2π and height 1.
The following equation defines the sinc function:

The sinc function has a value of 1 whenx is equal to zero, and a value of

28
% sinc
x = linspace(-5,5);
y = sinc(x);
subplot(1,2,1);plot(x,y)
xlabel(‘time’);
ylabel(‘amplitude’);
title(‘sinc function’);
subplot(1,2,2);stem(x,y);
xlabel(‘time’);
ylabel(‘amplitude’);
title(‘sinc function’);

Conclusion: In this experiment various signals have been generated Using MATLAB

Exercise Questions: Generate following signals using MATLAB

1. x(t)=e-t
2. x(t)= t 2 / 2
3. Generate rectangular pulse function
4. Generate signum sunction sinc(t)= 1t>0
0 t=0
-1 t<0
5. Generate complex exponential signal x(t)= e st for different values of σ

29
%% 1. BASIC SIGNALS %Unit Ramp
clc; for i=1:l1
close all; if (n(i)>=0)
clear all; x(i)=n(i);
n=-50:0.1:50; else
l1=length(n); x(i)=0;
t=0:0.1:2*pi; end
end
%Unit Impulse subplot(2,3,3);
for i=1:l1 plot(n,x,'r');
if (n(i)==0) xlabel("n");
x(i)=1; ylabel("x(n)");
else title("Ramp function");
x(i)=0;
end %Exponential
end subplot(2,3,4);
subplot(2,3,1); a=0:0.1:5;
plot(n,x); plot(a,exp(a),'b');
xlabel("n"); xlabel("t");
ylabel("x(n)"); ylabel("x(t)");
title("unit impulse"); title("Exponential signal");

%Unit step % Sine function


for i=1:l1 subplot(2,3,5);
if (n(i)<0) plot(t,sin(t),'c');
x(i)=0; xlabel("t");
else ylabel("x(t)");
x(i)=1; title("Sine signal");
end
end
subplot(2,3,2);
plot(n,x,'g'); % Cosine function
xlabel("n"); subplot(2,3,6);
ylabel("x(n)"); plot(t,cos(t),'m');
title("unit step"); xlabel("t");
ylabel("x(t)");
title("Cosine signal");

30
31
%% Sine and Cos Wave Generation
clc; clear all;
x=-pi:pi/20:pi;
y=sin(x);
subplot(2,1,1);
plot(x,y);

grid; axis([-pi,pi,-1,1]);
xlabel('time');
ylabel('amplitude');
title('sine wave generation');
y1=cos(x);
subplot(2,1,2);
plot(x,y1);

grid;
axis([-pi,pi,-1,1]);
xlabel('time');
ylabel('amplitude');
title('cos wave generation');

%% Sine and Cos Wave Generation in Discrete Form


clc;
clear all;
x=-pi:pi/20:pi;
y=sin(x);
subplot(2,1,1);

grid;
axis([-pi,pi,-1,1]);
stem(x,y);
xlabel('time');
ylabel('amplitude');
title('sine wave generation');
y1=cos(x);
subplot(2,1,2);
stem(x,y1);

grid; axis([-pi,pi,-1,1]);
xlabel('time');
ylabel('amplitude');
title('cos wave generation');

32
%% Sine wave with 2 harmonics and noise
clc; clear all; fs=1000;
ts=1/fs;
t=0:ts:1;
x=10*sin(2*pi*10*t)+10*sin(2*pi*2*10*t);
figure;
subplot(3,1,1);
plot(t,x);

grid;
xlabel('time');
ylabel('amplitude');

title('sine wave with 2 harmonics');


grid;
x1=x+randn(size(t));
subplot(3,1,2);
plot(t,x1);
grid;
xlabel('time');
ylabel('amplitude');
title('sin wave with noise');
subplot(3,1,3);

plot(t,x,t,x1);
grid;
xlabel('time');
ylabel('amplitude');

legend('sin wave with harmonics','sin wave with noise')

33
%% Sine wave with 2 harmonics and noise in Discrete Form
clc;
clear all;

fs = 1000;
ts = 1/fs;
t = 0:ts:0.1;

x=10*sin(2*pi*10*t)+10*sin(2*pi*2*10*t);
figure;
subplot(2,1,1);
stem(t, x);
grid;
xlabel('time');
ylabel('amplitude');
title('Sine wave with 2 harmonics');

x1 = x + randn(size(t));

subplot(2,1,2);
stem(t, x1);
grid;
xlabel('time');
ylabel('amplitude');
title('Sine wave with noise');

34
%% Sine wave with sampling frequency
clc;
clear all;
fs=1000;
ts=1/fs;
t=0:ts:1;
y=10*sin(2*pi*10*t);

figure;
stem(t,y);
grid;
xlabel('time');
ylabel('amplitude');
title('sine wave with sampling frequency'); axis([0 0.1 -10
10]);

35
36
Experiment No: 3
CONVOLUTION OF DISCRETE SIGNAL

Aim: To find the linear convolution of two discrete signals.


EQUIPMENTS:
• PC with operating system
• MATLAB Software

THEORY : Convolution is a mathematical operation that combines two input functions to


produce a third output function. In the context of discrete signals, such as digital images or
discrete-time signals in signal processing, convolution is used to process and manipulate
these signals.

Here's how it works:

Signals: Let's say we have two discrete signals, often referred to as the input signal (let's
call it "x") and the filter or kernel (let's call it "h"). These signals are sequences of values
indexed by integers. For example, x[0], x[1], x[2], ... and h[0], h[1], h[2], ...

Sliding and Multiplying: To compute the convolution, you take the filter and slide it
over the input signal. At each position, you perform element-wise multiplication between
the overlapping parts of the input signal and the filter.

Summation: After multiplying the overlapping portions, you sum up all the products.
This sum gives you the value of the convolution at that particular position.

Shifting: Now you shift the filter to the right (or left) and repeat the multiplication and
summation process. This shifting continues until the entire filter has been aligned with the
input signal.

Output Signal: The result of this process is a new signal, called the convolution output.
This output signal represents how much the filter "matches" or correlates with the input
signal at different positions.

Mathematically, the convolution of two discrete signals x[n] and h[n] is denoted by (x *
h)[n], and it can be defined as:

(x * h)[n] = Σ [x[k] * h[n - k]]

Here, the summation is taken over all possible values of k that ensure valid indexing of
the signals.

37
Code:
%% Convolution of two sequences
clc;
close all;
clear all;
x1=input('enter the 1st sequence');
x2=input('enter the 2nd sequence');
l1=length(x1);
l2=length(x2);
if(l1<l2)
X1=[x1,zeros(1,l2-l1)];
X2=x2;
else
X2=[x2,zeros(1,l1-l2)];
X1=x1;
end
c=conv(X1,X2);
stem(c);
title('convolution of two sequences');
xlabel('n');
ylabel('y(n)');

38
Input Output
enter the 1st sequence[1,2,3]
enter the 2nd sequence[0.5,0.5]

enter the 1st sequence[40,23,5,78]


enter the 2nd sequence[1,2,3,4]

enter the 1st sequence[14,10,2]


enter the 2nd sequence[7,8,9]

39
%Convolution of two sequences(w/o using direct function)
clc;
close all;
clear all;
x1 = input('Enter the 1st sequence: ');
x2 = input('Enter the 2nd sequence: ');
l1 = length(x1);
l2 = length(x2);

if l1 < l2
X1 = [x1, zeros(1, l2 - 1)];
X2 = x2;
m = l2;
else
X2 = [x2, zeros(1, l1 - 1)];
X1 = x1;
m = l1;
end

l = l1 + l2 - 1;
y = zeros(1, l);

for n = 1:l
for k = 1:l1
if (n - k + 1) > 0 && (n - k + 1) <= m
y(n) = y(n) + (X1(k) * X2(n - k + 1));
end
end
end

stem(y, 'r');
title('Convolution of two sequences');
xlabel('n');
ylabel('y(n)');

40
Input Output
enter the 1st sequence[1,2,3]
enter the 2nd sequence[0.5,0.5]

enter the 1st sequence[40,23,5,78]


enter the 2nd sequence[1,2,3,4]

enter the 1st sequence[14,10,2]


enter the 2nd sequence[7,8,9]

41
%%Convolution w/o using function
clc;
close all;
clear all;

X = input('Enter the input sequence: ');


n1 = input('Enter the time sample range: ');
h = input('Enter the impulse sequence: ');
n2 = input('Enter the time sample range: ');

z = [];

for i = 1:length(X)
g = h .* X(i);
z = [z; g];
end

[r, c] = size(z);
k = r + c;
t = 2;
y = [];
cd = 0;

while t <= k
for i = 1:r
for j = 1:c
if (i + j) == t
cd = cd + z(i, j);
end
end
end
t = t + 1;
y = [y cd];
cd = 0;
end

disp(y);

n3 = min(n1) + min(n2);
n4 = max(n1) + max(n2);
r = n3:1:n4;
stem(r, y);

42
Input Output
Enter the input sequence: [1,2,3]
Enter the time sample range: 1:3
Enter the impulse sequence: [0.5,0.5]
Enter the time sample range: 0:1

Enter the 1st sequence[40,23,5,78]


Enter the time sample range: 1:4
Enter the 2nd sequence[1,2,3,4]
Enter the time sample range: 0:3

enter the 1st sequence[14,10,2]


Enter the time sample range: 1:3
enter the 2nd sequence[7,8,9]
Enter the time sample range: 0:2

43
Experiment No: 4
CORRELATION OF DISCRETE SIGNAL

Aim: To find the correlation of two discrete signals.


EQUIPMENTS:
• PC with operating system
• MATLAB Software

THEORY :

The correlation of two functions or signals or waveforms is defined as the measure of similarity
between those signals. There are two types of correlations −

Cross-correlation
The cross-correlation between two different signals or functions or waveforms is defined as the
measure of similarity or coherence between one signal and the time-delayed version of another
signal. The cross-correlation between two different signals indicates the degree of relatedness
between one signal and the time-delayed version of another signal.

The cross-correlation of energy (or aperiodic) signals and power (or periodic) signals is defined
separately.

Discrete cross-correlation formula:

Autocorrelation
The autocorrelation function is defined as the measure of similarity or coherence between a signal
and its time delayed version. Therefore, the autocorrelation is the correlation of a signal with itself.

Like cross-correlation, autocorrelation is also defined separately for energy (or aperiodic) signals
and power (periodic) signals.

Discrete autocorrelation formula:

44
Code:
%% Auto-Correlation w/o using direct function
clear all;
close all;
clc;
x=input('Enter the sequence x(n)')
n = length(x);
m = 2*n - 1;
rxx = zeros(1,m);
for i = 1:length(x)
rxx(i) = dot(x(n-i+1:n), x(1:i).');
rxx(m-i+1) = rxx(i)';
end
subplot(3,1,1)
stem(rxx)
xlabel('time')
ylabel('amplitude')
Input:
Enter the sequence x(n)[28,76,45,90]
Output:

45
%% Cross Correlation w/o function
clear all;
close all;
clc;
x=input('enter the value of 1st sequence');
j=input('enter the value of 2nd sequence');
h=fliplr(j);
disp('the 1st sequence is-');
disp(x);
disp('the 2nd sequence is-');
disp(j);
lx=length(x);
lh=length(h);
n=lx+lh-1;
subplot(3,1,1);
stem(x);
title('1st sequence');
subplot(3,1,2);
stem(j);
title('2nd sequence');
hh=[h zeros(1,n-lh)];
xx=zeros(n);
xx(1:lx,1)=x;
for i=2:n
for j=2:n
xx(j,i)=xx(j-1,i-1);

end;
end;
yy=xx*hh';
subplot(3,1,3);
stem(yy);
disp('cross correlate o/p->');
disp(yy');
title('y=cross correlastion of x & j');
Input:
enter the 1st sequence[1,2,3,4,5]
enter the 2nd sequence[28,76,45,90]
Output:

46
%% Correlation using direct function
clc;
close all;
clear all;
x1=input('enter the 1st sequence');
x2=input('enter the 2nd sequence');
l1=length(x1);
l2=length(x2);
if (l1<l2)
X1=[x1,zeros(1,l2-l1)]
X2=x2;
end
if (l1>=l2)
X2=[x2,zeros(1,l1-l2)]
X1=x1;
end
cross=xcorr(X1,X2);
auto1=xcorr(X1,X1);
auto2=xcorr(X2,X2);
subplot(3,1,1);
stem(cross);
title('Cross-Correlation of two signals X1 and X2')
xlabel('n')
ylabel('y(n)')
subplot(3,1,2);
stem(auto1);
title('Auto-Correlation of signal X1')
xlabel('n')
ylabel('y(n)')
subplot(3,1,3);
stem(auto2);
title('Auto-Correlation of signal X2')
xlabel('n')
ylabel('y(n)')
Input:
enter the 1st sequence[1,2,3,4,5]
enter the 2nd sequence[28,76,45,90]
Output:

47
Experiment No: 5
CIRCULAR CONVOLUTION OF DISCRETE SIGNAL

Aim: To find the circular convolution of two discrete signals.

EQUIPMENTS:
 PC with operating system
 MATLAB Software

THEORY :

Circular convolution is a fundamental mathematical operation in the field of signal processing, particularly suited for
handling periodic signals. It allows for the combination of two discrete time signals under the assumption that both
signals exhibit periodic behavior. Unlike linear convolution, which necessitates adjusting signal lengths through zero-
padding or truncation, circular convolution treats signals as if they repeat infinitely.

The process of circular convolution involves cyclically shifting one signal with respect to the other.
At each position of this circular shift, element-wise multiplication is performed between the corresponding
values of the two signals, and these products are then summed.
This operation continues for all possible circular shifts, ultimately yielding a new signal that encapsulates the
collective impact of the input signals.

Circular convolution proves highly valuable in practical applications where signals exhibit recurring patterns.

For example, in communication systems, circular convolution helps analyze how signals propagate through
transmission channels with cyclic properties. In audio processing, circular convolution can be used to
simulate the effects of room acoustics or to apply audio effects in a manner that respects the periodic nature
of sound waves.

Furthermore, circular convolution simplifies the treatment of periodic signals by taking into account their
cyclical behavior, eliminating the need for complex adjustments to handle signals with varying lengths.
It provides a powerful tool for understanding and manipulating signals in cases where periodicity plays a
significant role.

Circular Convolution can be performed in three different ways:


By matrix method
By concentric circle method
By DFT

48
Code:
By using Concentric Circle method:
%circular convolution
%using concentric circle method
clc;
close all;
clear all;
x=input("Enter the first sequence");
y=input("Enter the second sequence");
l1=length(x);
l2=length(y);
if (l1<l2)
X=[x,zeros(1,l2-l1)];
Y=y;
cir=zeros(1,l2);
l=l2;
end
if (l1>=l2)
Y=[y,zeros(1,l1-l2)];
X=x;
cir=zeros(1,l1);
l=l1;
end

c=1;
d=1;
for i=1:l
c=i;
d=1;
for j=1:l
cir(i)=cir(i)+X(d)*Y(c);
if(c<l)
c=c+1;
else
c=1;
end
d=d+1;
end
end
stem(cir);
title('circular convolution of two sequences using concentric circle method');
xlabel('n');
ylabel('y(n)');

49
Input:
Enter the first sequence[1 2 4 2]
Enter the second sequence[1 1 1]
Output:

By using matrix method:


%circular convolution
%using matrix method
clc;
close all;
clear all;
x=input("Enter the first sequence");
y=input("Enter the second sequence");
l1=length(x);
l2=length(y);
if (l1<l2)
X=[x,zeros(1,l2-l1)];
X=X';
Y=y';
l=l2;
else
Y=[y,zeros(1,l1-l2)];
Y=Y';
X=x';
l=l1;
end
% Initialize the matrix with zeros
result_matrix = zeros(l, l);
% Fill the matrix with shifted columns
for i = 1:l
result_matrix(:, i) = circshift(X, i - 1);
end
cir=result_matrix*Y;
stem(cir);
title('circular convolution of two sequences using matrix method');
xlabel('n');
ylabel('y(n)');

50
Input:
Enter the first sequence[1 2 4 2]
Enter the second sequence[1 1 1]
Output:

51
Experiment No: 5
FOURIER TRANFORM OF DISCRETE SIGNAL

Aim: To find Fourier Transform of Discrete Signals.


EQUIPMENTS:
 PC with operating system
 MATLAB Software

THEORY :

The discrete Fourier transform (DTFT)of a sequence is a continuous of form of w, and repeats with period 2
pi. In practice we usually want to obtain the Fourier components using digital computation, and can evaluate
them for a discrete set of frequencies. The discrete Fourier transform (DTFT)provides a means for achieving
this.

The DFT is itself a sequence and it corresponds roughly to sample, equally sampled in frequency of the
Fourier transform of the signal. The discrete Fourier of length x[n], n=0,1,…N-1 given by
𝑛−1
𝜋
x[n]= ∑ x[n]^e(−𝑗 (2̂ 𝑛 ) 𝑘𝑛)
𝑛=0

This is the analysis equation.The correspondong inverse equation is


𝑛−1
𝜋
x[n]=1/N( ∑ x[n]^e(𝑗 (2̂ 𝑛 ) 𝑘𝑛))
𝑛=0

Code:

%DFT

clc;
clear all;
close all;
x1=input('Enter the input sequence');
N=length(x1);
for k=0:1:N-1
for n=0:1:N-1
p=exp(-i*2*pi*n*k/N);
x2(k+1,n+1)=p;
end
end
Y=(x1*x2);
k=0:1:N-1;
subplot(2,1,1)
stem(k,abs(Y))
xlabel('k')
ylabel('phase')

52
Enter the input sequence [1,2,1,3]

%% IDFT
clear all
x1=input(‘enter the input sequence’)
N=length(x1)
for k=0:1:N-1
for n=0:1:N-1
p=exp(i*2*pi*n*k/N)
x2(k+1,n+1)=p
end
end
Y=(x1*x2)/N
k=0:1:N-1
subplot(2,1,1)
stem(k,abs(Y))
xlabel('k')
ylabel('amplitude')
subplot(2,1,2)
stem(k,angle(Y))
xlabel('k')
ylabel('phase')

Enter the input sequence [1,2,1,3]

53
% Finding the FFT of a given signal and plotting its magnitude and phase spectrum
clc;
clear all;
close all;
x=input('Enter the sequence : ')
N=length(x)
xK=fft(x,N)
xn=ifft(xK)
subplot(3,1,1)
stem(abs(xK))
title('Magnitude of Fourier Spectrum')
xlabel('frequency')
ylabel('Magnitude')
subplot(3,1,2)
stem(angle(xK))
title('Phase of Fourier Spectrum')
xlabel('frequency')
ylabel('phase')
subplot(3,1,3)
stem(xn)
title('Inverse FFT')
xlabel('time');
ylabel('amplitude');

Enter the input sequence [1,2,1,3]

54
55

You might also like