0% found this document useful (0 votes)
15 views103 pages

MATLAB Lab Manual for Mechanical Engineering

The document is a lab manual for the Basics of MATLAB course (21ME581) at Rajeev Institute of Technology, designed for V Semester Mechanical Engineering students. It outlines the course objectives, experiments, program outcomes, and educational objectives, emphasizing the importance of MATLAB in engineering applications. Additionally, it includes guidelines for lab conduct and a detailed syllabus of experiments to be conducted during the course.

Uploaded by

bellali badre
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views103 pages

MATLAB Lab Manual for Mechanical Engineering

The document is a lab manual for the Basics of MATLAB course (21ME581) at Rajeev Institute of Technology, designed for V Semester Mechanical Engineering students. It outlines the course objectives, experiments, program outcomes, and educational objectives, emphasizing the importance of MATLAB in engineering applications. Additionally, it includes guidelines for lab conduct and a detailed syllabus of experiments to be conducted during the course.

Uploaded by

bellali badre
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

RAJEEV INSTITUTE OF TECHNOLOGY

HASSAN-573201

BASICS OF MATLAB LAB MANUAL


(21ME581)
As per VTU Syllabus CBCS scheme for V Semester

DEPARTMENT OF
MECHANICAL ENGINEERING
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
RAJEEV INSTITUTE OF TECHNOLOGY
HASSAN-573201

BASICS OF MATLAB LAB MANUAL


(21ME581)
As per VTU Syllabus CBCS scheme for V Semester

Name:……………………………………………………….

USN:……………………………………………………..

Semester:…………… Batch No. .……………….

Mr. Hanoca P Mr. Dinesh R


Faculty Incharge Lab Instructor

DEPARTMENT OF
MECHANICAL ENGINEERING
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME

VISION & MISSION OF THE INSTITUTE


Vision:
 To be an academic institution in vibrant social & economic environment, striving
continuously for excellence in education, research and technological service to the
society

Mission:
1. To achieve academic excellence in engineering and management through dedication
to duty, offering state of the art education and faith in human values

2. To create and endure a community of learning among students, develop outstanding


professionals with high ethical standards
3. To provide academic ambience conducive to the development, needs and growth of
society and the industry

VISION & MISSION OF THE DEPARTMENT

Vision:
 To become a center of excellence in educating students to become successful
Mechanical engineers for the benefit of society.

Mission:
1. To provide the students with the fundamental knowledge necessary for a successful
career in mechanical engineering.

2. To empower students for higher education and active research development to contribute to the
engineering profession and society.

MAHESH P K
30.05.2024 16:13
Department of Mechanical Engineering, Rajeev Institute
Digitally of Technology,
Signed by Hassan. i
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME

PROGRAM SPECIFIC OUTCOMES (PSO’S)

The graduates of Mechanical engineering program of Rajeev Institute of Technology should be


able to attain the following at the time of graduation.

PSO1: The ability to create novel materials, mechanical systems, and processes using a
multidisciplinary approach that is beneficial to society.

PSO2: Through various courses, projects, and internships, gain practical and hands-on exposure
to various Mechanical tools, control methods, equipment, and simulation software.

PROGRAM EDUCATIONAL OBJECTIVES (PEO’S)

The program educational objectives are the statements that describe the expected achievements
of graduates within first few years of their graduation from the program. The program
educational objectives of Bachelor of Mechanical Engineering at Rajeev Institute of Technology
can be broadly defined as,

PEO 1: Successful professional careers as mechanical engineers with a sound knowledge of


current technology with a focus on research and innovation.

PEO 2: An ability to embrace professional and ethical attitude with awareness of societal
impact

PEO 3: Graduate shall be pursuing advanced education, engage in multi-disciplinary research


activities& zeal for lifelong learning.

MAHESH P K
30.05.2024 16:13
Department of Mechanical Engineering, Rajeev Institute
Digitally of Technology,
Signed by Hassan. ii
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
B. E. MECHANICAL ENGINEERING
Choice Based Credit System (CBCS) And Outcome Based Education (OBE)
SEMESTER – V
BASICS OF MATLAB (Ability Enhancement Course)
Course Code 21ME581 CIE Marks 50
Teaching Hours/Week (0:0:2) SEE Marks 50
(L:T:P)
Credits 01 Exam Hours 03
Course objectives:
1. To know about fundamentals of MATLAB tool.
2. To provide an overview to program curve fitting & solve Linear and Nonlinear Equations.
3. To understand the concept and importance of Fourier transforms.
4. To gain knowledge about MATLAB Simulink & solve Electrical engineering problems.

Sl. No. Experiments


1. Introduction to MATLAB Programming: Basics of MATLAB Programming, array
operations in MATLAB, loops and execution of control, working with files: Scripts
and functions, plotting and programming output, examples.
2. Numerical Methods and their applications: Curve Fitting: Straight line fit,
Polynomial fit
3. Numerical Integration and Differentiation: Trapezoidal method, Simpson method
4. Linear and Nonlinear Equations: Eigen values, Eigen vectors, Solution of linear
algebraic equations using Gauss Elimination and LU decomposition, Solution of
nonlinear equation in single variable using Gauss-Siedal and Newton-Raphson
method.
5. Ordinary Differential Equations: Introduction to ODE’s, Euler’s method, second
order RungaKutta method, MATLAB ode45 algorithm in single variable and
multivariables. Transforms: Discrete Fourier Transforms,
6. Application of MATLAB to analyse problems in basic engineering mechanics,
mechanical vibrations, control system, statistics and dynamics of different circuits.
MATLAB Simulink: Introduction to MATLAB Simulink, Simulink libraries,
development of basic models in Simscape Power Systems

Text Books:
1. Agam Kumar Tyagi, “MATLAB and Simulink for Engineers”, OXFORD Higher Education.
2. Dr. Shailendra Jain, “Modeling& Simulation using MATLAB – Simulink”, Wiley – India.
Reference Books:
1. Won [Link], Wemun Cao, Tae-Sang Ching and John Morris, “Applied Numerical Methods
Using MATLAB”, A John Wiley & Sons.
2. Steven T. Karris, “Introduction to Simulink with Engineering Applications”, Orchard
Publications.
MAHESH P K
30.05.2024 16:13
Department of Mechanical Engineering, Rajeev Institute
Digitally of Technology,
Signed by Hassan. iii
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
COURSE OUTCOMES (Course Skill Set):
At the end of the course the student will be able to:
CO1. Able to implement loops, branching, control instruction and functions in MATLAB
programming environment.
CO2. Able to program curve fitting, numerical differentiation, integration, solution of linear
equations and ODE, stimulate MATLAB Simulink in MATLAB

Assessment Details (both CIE and SEE): The weightage of Continuous Internal Evaluation
(CIE) is 50% and for Semester End Exam (SEE) is 50%.
Continuous Internal Evaluation (CIE): CIE marks for the practical course is 50 Marks. The
split-up of CIE marks for record/ journal and test are in the ratio 60:40. Total marks for the
record is 30 marks. 02 tests are conducted for 100 marks, the average of 02 tests is scaled down
to 20 marks.

The Correlation of Course Outcomes (CO’s) and Program Outcomes (PO’s)


Course Code:
21ME581
TITLE: BASICS OF MATLAB
List of Program Outcomes
Course PO PO PO PO PO PO PO PO PO PO1 PO PO Total
Outcomes 1 2 3 4 5 6 7 8 9 0 11 12
CO-1 2 1 03
CO-2 2 2 04
Total 4 3 7

Note:
High Contribution = 3, Average Contribution = 2, Low Contribution = 1, No Contribution =0

The Correlation of Course Outcomes (CO’s) and Program Specific Outcomes (PSO’s)
Course Code:
21ME581
TITLE: BASICS OF MATLAB
List of Program Specific Outcomes
Course
PSO1 PSO2 Total
Outcomes
CO-1 2 0 2
CO-2 2 0 2
Total 6 0 6

MAHESH P K
30.05.2024 16:13
Department of Mechanical Engineering, Rajeev Institute
Digitally of Technology,
Signed by Hassan. iv
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME

DO’s

1. Treat computers and other equipment with care and respect. Avoid tampering with
hardware or software unless authorized.
2. Adhere to all posted rules and guidelines for computer lab usage. These may include
restrictions on food and drink, noise levels, and appropriate behavior.
3. Report any technical problems or malfunctions to lab staff promptly. This helps maintain
the equipment and ensures a smooth experience for all users.
4. Keep noise levels down to avoid disturbing others who are working or studying in the lab.
5. Clean up your area before leaving, disposing of trash and ensuring the workstation is tidy
for the next user.
DONT’s

1. Do not download or install software without permission from lab administrators.


Unauthorized software can pose security risks and may violate licensing agreements.
2. Avoid activities such as hacking, unauthorized network access, or any other actions that
violate the lab's acceptable use policy or local laws.
3. Never leave personal belongings or devices unattended in the lab. This reduces the risk of
theft or tampering.
4. Share Login Credentials: Keep your login credentials private and do not share them with
others. Sharing credentials can compromise security and lead to unauthorized access.
5. Do not misuse lab equipment for activities such as gaming, watching inappropriate content,
or engaging in non-academic tasks unrelated to the lab's purpose.
6. Ignoring posted rules and guidelines can result in loss of lab privileges or disciplinary
action.

MAHESH P K
30.05.2024 16:13
Department of Mechanical Engineering, Rajeev Institute
Digitally of Technology,
Signed by Hassan. v
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME

CONTENTS
Expt. TITLE Page No.
No.
Vision & Mission of the Institute & Department i

Department PSO’s & PEO’s ii

Syllabus iii

Do’s & Dont’s v

Contents vi

EXPERIMENTS

1. INTRODUCTION TO MATLAB 1

2. CURVE FITTING 13

3. NUMERICAL INTEGRATION 17

4. LINEAR AND NONLINEAR EQUATIONS 20

5. ORDINARY DIFFERENTIAL EQUATIONS 24

MAHESH P K
30.05.2024 16:13
Department of Mechanical Engineering, Rajeev Institute
Digitally of Technology,
Signed by Hassan. vi
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
Program 1
INTRODUCTION TO MATLAB
Introduction
MATLAB is a high-performance language for technical computing. It integrates computation,
visualization, and programming in an easy-to-use environment where problems and solutions are
expressed in familiar mathematical notation. The name MATLAB stands for matrix laboratory.
MATLAB was originally written to provide easy access to matrix.
Starting and Quitting MATLAB

• To start MATLAB, double-click the MATLAB shortcut icon on your Windows


desktop.
• To end your MATLAB session, select Exit MATLAB from the File menu in the desktop.
Desktop Tools
1- Command Window: Use the Command Window to enter variables and run functions and M-
files.
2- Command History: Statements you enter in the Command Window are logged in the
Command History. In the Command History, you can view previously run statements, and
copy and execute selected statements.
3- Current Directory Browser: MATLAB file operations use the current directory reference
point. Any file you want to run must be in the current directory or on the search path.
Workspace: The MATLAB workspace consists of the set of variables (named arrays) built up
during a MATLAB session and stored in memory.
Basic Commands
• clear Command: Removes all variables from workspace.
• clc Command: Clears the Command window and homes the cursor.
• help Command: help <Topic> displays help about that Topic if it exist.
• lookfor Command: Provides help by searching through all the first lines of MATLAB help
topics and returning those that contains a key word you specify.

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 1
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME

Creating MATLAB variables


variable name = a value (or an expression)
x = expression
Hierarchy of arithmetic operations
The Bodmas rule follows the order of the BODMAS acronym ie B – Brackets, O – Order of powers
or roots, D – Division, M – Multiplication A – Addition, and S – Subtraction. Mathematical
expressions with multiple operators need to be solved from left to right in the order of BODMAS.

Controlling the appearance of floating point number

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 2
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
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

Mathematical functions

Solve the below expression using MATLAB

( ) √ where, a = 10, x = 10, and y = 20


>> z = exp(-a) * sin(x) + 10*sqrt(y)
>> z = 44.7213
Basic plotting
MATLAB has an excellent set of graphic tools. Plotting a given data set or the results of
computation is possible with very few commands.
The MATLAB command to plot a graph is plot(x,y). The vectors x = (1; 2; 3; 4; 5; 6) and
y = (3;-1; 2; 4; 5; 1) produce the picture shown in Figure
x = [1 2 3 4 5 6];
y = [3 -1 2 4 5 1];
plot(x,y)
MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 3
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME

Notes:
0:pi/100:2*pi yields a vector that
starts at 0,
takes steps (or increments) of Pi/100, stops when 2Pi is reached.
If you omit the increment, MATLAB automatically increments by 1.
Adding titles, axis labels, and annotations
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y);
xlabel('x = 0:2\pi');
ylabel('Sine of x');
title('Plot of the Sine function');
Plot of the Sine function
1

0.8

0.6

0.4

0.2
Sine of x

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7
x = 0:2

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 4
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
Multiple data sets in one plot
x = 0:pi/100:2*pi;
y1 = 2*cos(x);
y2 = cos(x);
y3 = 0.5*cos(x);
plot(x,y1,'--',x,y2,'-',x,y3,':')
xlabel('0 \leq x \leq 2\pi');
ylabel('Cosine functions');
legend('2*cos(x) ', 'cos(x) ', '0.5*cos(x) ');
title('Typical example of multiple plots');
axis([0 2*pi -3 3]);
Typical example of multiple plots
3
2*cos(x)
cos(x)
2 0.5*cos(x)

1
Cosine functions

-1

-2

-3
0 1 2 3 4 5 6
0  x  2

Specifying line styles and colors


plot(x,y,’style_color_marker’)
style_color_marker is a triplet of values
MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 5
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
Working with Matrices
Entering Matrix
The best way for you to get started with MATLAB is to learn how to handle matrices. You only
have to follow a few basic conventions:
• Separate the elements of a row with blanks or commas.
• Use a semicolon ( ; ) to indicate the end of each row.
• Surround the entire list of elements with square brackets, [ ].
For Example
>> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
MATLAB displays the matrix you just entered
A=
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
Colon Operator
The colon " : " is one of the most important MATLAB operators. It occurs in several different
forms. The expression
>> 1:10
is a row vector containing the integers from 1 to 10
1 2 3 4 5 6 7 8 9 10

To obtain non unit spacing, specify an increment. For example,


>> 100:-7:50
100 93 86 79 72 65 58 51
Transposing a matrix
The transpose operation is denoted by an apostrophe or a single quote (’). It flips a matrix
about its main diagonal and it turns a row vector into a column vector. Thus,
>> A’
Ans =
16 5 9 4
3 10 6 15
2 11 7 14
13 8 12 1
MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 6
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
Matrix inverse
Let’s consider matrix A = [1 2 3; 4 5 6; 7 8 0];
% Matlab program for the inverse of A is
inv(A)
ans =
-1.7778 0.8889 -0.1111
1.5556 -0.7778 0.2222
-0.1111 0.2222 -0.1111
Matrix arithmetic operations
MATLAB allows arithmetic operations: +, -, ⁄, and ^ to be carried out on matrices.
Thus,
A+B or B+A is valid if A and B are of the same size
A*B is valid if A’s number of column equals B’s number of rows
A^2 is valid if A is square and equals A*A
Array arithmetic operations are done element-by-element. The period character '.' distinguishes
the array operations from the matrix operations. However, since the matrix and array operations are
the same for addition (+) and subtraction (¡), the character pairs (.+) and (.-) are not used. The list of
array operators is shown below in Table. If A and B are two matrices of the same size with elements
A = [aij] and B = [bij], then the command
.* Element-by-element multiplication
./ Element-by-element division
.^ Element-by-element exponentiation
For Example:
A = [ 1 2 3 ; 4 5 6 ; 7 8 9] and B = [10 20 30 ; 40 50 60 ; 70 80 90]
>> C = A.*B
C=
10 40 90
160 250 360
490 640 810
Operations Matrix Array
Addition + +
Subtraction - -
Multiplication * .*

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 7
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
Division / .*
Left division \ .\
Exponentiation ^ .^

MATLAB program on solving the linear equations


Solve the following linear equations:
x + 2y + 3z =1
4x + 5y + 6z =1
7x + 8y =1
MATLAB program is
1. Input coefficient of matrix A and b
A = [1 2 3; 4 5 6; 7 8 0];
b = [1; 1; 1];
2. Ax = b , This equation can be solved for x using linear algebra. The result is x = A-1 b
x = inv(A)*b
ans x =
-1.0000
1.0000
-0.0000
Control flow
MATLAB has four control flow structures: the if statement, the for loop, the while loop, and the
switch statement.
IF Condition

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 8
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
MATLAB program is
a =2, b= 16, c = 4;
discr = b*b - 4*a*c;
discr;
if discr < 0
disp('Warning: discriminant is negative, roots are imaginary');
end
IF ELSE Condition

MATLAB program is
a =8, b= 100, c = 4;
x = b*b - 4*a*c;
disp('x =');
disp (x);
if x < 0
disp('Warning: discriminant is negative, roots are imaginary');
else
disp('Roots are real, but may be repeated')
end

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 9
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
IF, ELSEIF, ELSE Condition

MATLAB program is
a =1, b= 4, c = 4;
x = b*b - 4*a*c;
disp('x =');
disp (x);
if x < 0
disp('Warning: discriminant is negative, roots are imaginary');
elseif x == 0
disp('’Discriminant is zero, roots are repeated’');
else
disp('Roots are real, but may be repeated');
end
FOR LOOP
With for loop control statements, you can repeatedly execute a block of code number of times.
Syntax
for index = start: increment: stop
statements
end
Example: Write a MATLAB program to find the factorial of 10 using for loop
n = 10;
fact = 1;
for k = 1:n
fact = fact *k;
end
MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 10
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
disp(fact )
Ans
fact =
while loop
While loop is a conditional loop repeating when condition is true.
Syntax
while test
statements
end
Example: Write a MATLAB program to find the factorial of 10 using while loop
fact = 1;
k=1
while k <=10
fact = fact *k;
k=k+1
end
disp(fact )
Example: Write a program that find the value of x using function, where

Where, n = 5, r = 3
( )

n = 5;
factn = 1;
for k = 1:n
factn = factn *k;
end
fprintf('factn = %d\n',factn);
r = 3;
factr = 1;
for k = 1:r
factr = factr *k;
end
MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 11
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
fprintf('factr = %d\n',factr);
q = n-r;
factq = 1;
for k = 1:q
factq = factq *k;
end
fprintf('factq = %f\n',factq);
x = factn/(factr*factq);
fprintf('x = %f\n',x);

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 12
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
Program 2
NUMERICAL METHODS AND THEIR APPLICATIONS:
CURVE FITTING: STRAIGHT LINE FIT, POLYNOMIAL FIT
MATLAB Program on Curve Fitting by Straight Line Fit Method
Aim: Understand and implementation of a straight-line fit using MATLAB. Use of the ‘polyfit’
functions to fit a polynomial to a set of data points.
Prerequisites: Concepts of a straight-line equation (y = mx + b).
Procedure:
1. Open MATLAB:
2. Load or Input Data:
% Sample data
x = [1, 2, 3, 4, 5];
y = [2, 4, 5, 4, 5];
3. Linear Regression (Straight-Line Fit):
Use the polyfit function to perform linear regression and fit a straight line to the data.
% Linear regression (straight-line fit)
coefficients = polyfit(x, y, 1);
4. Extract Slope and Intercept:
Extract the slope and y-intercept from the resulting coefficients.
% Extracting slope and y-intercept
slope = coefficients(1);
intercept = coefficients(2);
5. Display the Results:
Print out the equation of the fitted line.
fprintf('Linear Fit Equation: y = %.2fx + %.2f\n', slope, intercept);
6. Plotting:
Plot the original data points and the fitted line.
scatter(x, y, 'o', 'DisplayName', 'Data Points');
hold on;
fitted_line = polyval(coefficients, x);
plot(x, fitted_line, 'r-', 'DisplayName', 'Linear Fit');
xlabel('x');
ylabel('y');
MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 13
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
legend('show');
grid on;
7. Run the Entire Script: Save your script and run the entire program. Observe the plot generated
and analyze the linear fit.
Results: Plot the curve

5.5
Data Points
Linear Fit
5

4.5

4
y

3.5

2.5

2
1 1.5 2 2.5 3 3.5 4 4.5 5
x

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 14
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
MATLAB Program on Curve Fitting by Polynomial Fit Method
Aim: Understand and implement polynomial curve fitting using MATLAB. Use of the polyfit and
polyval functions to fit a polynomial to a set of data points
Prerequisites: concepts of polynomial regression
Procedure:
1. Open MATLAB
2. Load or Input Data:
% Sample data
x = [1, 2, 3, 4, 5];
y = [2, 4, 5, 4, 5];
% Here, x and y are arrays representing the input and output data points.
3. % Polynomial regression (cubic fit)
degree = 3; % Degree of the polynomial
coefficients = polyfit(x, y, degree);
% The polyfit function is used for polynomial regression. In this case, it fits a polynomial of degree
3 (cubic polynomial) to the data points (x, y). The resulting coefficients are stored in the array
coefficients.
4. % Display the polynomial coefficients
fprintf('Polynomial Coefficients (from high to low degree):\n');
disp(coefficients);
%This prints out the coefficients of the polynomial in descending order of degree.
5. % Generate a set of x values for smoother plotting
x_values = linspace(min(x), max(x), 100);
% It generates 100 evenly spaced x values within the range of the original data. This is done to
create a smooth curve for visualization.
6. % Evaluate the polynomial at the new x values
fitted_curve = polyval(coefficients, x_values);
% The polyval function is used to evaluate the polynomial defined by the coefficients at the new
x_values. This creates the y values for the fitted polynomial curve.
7. % Plotting the data and the fitted polynomial curve
scatter(x, y, 'o', 'DisplayName', 'Data Points');
hold on;
plot(x_values, fitted_curve, 'r-', 'DisplayName', 'Polynomial Fit');
xlabel('x');
MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 15
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
ylabel('y');
legend('show');
grid on;
8. Run the Entire Script: Save your script and run the entire program. Observe the plot
generated and analyze the polynomial fit.
% This code plots the original data points as circles ('o') and the fitted polynomial curve as a red
line ('r-'). It also adds labels, a legend, and grid for better visualization.
Results: Plot the curves for different degree
Degree 3

5
Data Points
Polynomial Fit
4.5

3.5
y

2.5

1.5
1 1.5 2 2.5 3 3.5 4 4.5 5
x

Degree 4

5.5
Data Points
Polynomial Fit
5

4.5

4
y

3.5

2.5

2
1 1.5 2 2.5 3 3.5 4 4.5 5
x

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 16
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
Program 3
NUMERICAL INTEGRATION AND DIFFERENTIATION:
TRAPEZOIDAL METHOD, SIMPSON METHOD
MATLAB Program on Numerical Integration by Trapezoidal method
Aim: Understand and implementation of a Trapezoidal method using MATLAB.

Matlab program to solve the below expression using Trapezoidal method:

( ) ∫

format short
clear all;
clc;
%f= @(x)1./(1+x);
f= @(x)x.^2;
a = input(' Enter Lower Limit a: ')
b = input(' Enter Upper Limit b: ')
n = input ('Enter the no. of subinterval: ');
h = (b-a)/n;
i = 1:1:n-1;
s = f(a+i.*h);
out = (h./2).*(f(a)+2.*sum(s)+f(b));
fprintf('The value of integration is %f \n', out);
Result

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 17
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
MATLAB Program on Numerical Integration by Simpson method
Aim: Understand and implementation of a Simpson method using MATLAB.
Theory:
In mathematics, the Simpson’s 1/3 rule is a numerical integration method, that is a method to
calculate approximately the value of the definite integral.

∫ ( )

Simpson’s 1/3 rule approximate the integral of f(x) by taking the curve which pass through the
points (x0, f(x0)), (x1,f(x1)) and (x2, f(x2)) as polynomial of degree2 so that the differenced of order 3
and greater than 3 becomes zero.

∫ ( ) [ ( ) ( ( ) ( ) )

[ ( ) ( ) ] ( )]

∫ ( ) [ ( ) ( ) [ ] ( )]

Matlab program to solve the below expression using Simpson’s 1/3rd method:

( ) ∫ ( ) ( ) ( )

format short
clear all;
clc;
f = @(x) cos (x) - log(x) + exp(x);
a = input(' Enter Lower Limit a: ')
b = input(' Enter Upper Limit b: ')
n = input ('Enter the no. of subinterval: ');
h = (b-a)/n;
if rem(n,2)==1
fprintf('\n Please enter even number for n');
n = input('\n Enter n as even number ');
end
k = 1:1:n-1;
s = f(a+k.*h);
se = sum(s(2:2:n-1));
so = sum(s(1:2:n-1));
MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 18
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
out = (h/3).*(f(a)+f(b)+2.*so+4.*se);
fprintf('The value of integration is %f\n', out);
Result

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 19
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
Program 4
LINEAR AND NONLINEAR EQUATIONS
MATLAB Program to find Eigen values and Eigen vector for the given square matrix.
Aim: To understand how to find the eigenvalues of a square matrix using MATLAB.
Prerequisites: Basic knowledge of linear algebra
Procedure:
1. Open MATLAB:
2. Define a Square Matrix
% Sample data
A = [4 -2 4; 1 1 2; 5 3 2];
3. Find Eigen values
%Use the eig function to find the eigenvalues of the matrix [A]
[eigenvectors, eigenvalues] = eig(A);
4. Display the Results:
disp('Eigenvectors:');
disp(eigenvectors);
disp('Eigenvalues:');
disp(eigenvalues);
5. Run the Program
6. Interpretation: Interpret the result. The displayed eigenvalues are the solutions to the
characteristic equation of the matrix.
Results:

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 20
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
MATLAB Program to find linear algebraic equations using Gauss Elimination method
Aim: Understand and implementation of a Gauss Elimination method using MATLAB.

MATLAB Program to solve the below expression using Gauss Elimination method:
6x1 + 3x2 + 2x3 =6
6x1 + 4x2 +3x3 = 0
20x1+15x2+12x3 = 0

format short
clear all
clc
Info = [ 6 3 2; 6 4 3; 20 15 12]; % given matrix A
B = [ 6; 0; 0]; % RHS of the system of equations
A = [ Info B];
for i = 1: size(A,1)
for j = i+1:size(A,1)
key1 = A(j,i)./A(i,i);
A(j,:) = A (j,:)-key1.*A(i,:);
end
end
x = zeros(1,size(Info,2));
for i = size (A,1):-1:1
hg = sum(A(i,i+1:end-1).*x(i+1:end));
x(i) = (A(i,end)-hg)./A(i,i);
end
fprintf('solution is x =%d \n', x)
Results:

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 21
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
MATLAB Program to find Non - linear algebraic equations using Newton Rapson method
Aim: Understand and implementation of a Newton Rapson method using MATLAB.
Theory:
Foe a function f(x) = 0,
The iterative scheme of the Newton- Raphson’s method
( )
( )
Where x0 is the initial point such that
( )
Find the root of the equation: using Newton – Raphson’s method correct up
to four decimal places.

format short
clear all
clc
syms x
% write the function here
f = @(x) x*log10(x)-1.2;
df = diff(f,x);
dfx = inline(df);

x0 = 1.5; % Initial Guess


n = 4 % number of decimal place
variables = {'iter','x','f_x0', 'Error'};
iter = 1; % set the initial iteration counter
err = abs (f(x0)); % compute the initial error
epsilon = 5*10^(-n-1); % Maximum Tolerance error upto "n" decimal accuracy
itermax = 70; % Maximum number of iterations performed
HG = [];
if dfx(x0)<10^(-9) % Derivative shold be non zero
disp ('wrong choice of initial guess');
else
while (iter<=itermax && err > epsilon)
x1 = x0 -f(x0)/dfx(x0); % Compute new root

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 22
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
err = abs (f(x0));
HG = [HG;iter x0 f(x0) err]; % for printing purpose
iter = iter+1; % update the iteration counter
x0 = x1; % Update point
end
end

% for printing purpose


disp('=========================================')
disp('Output table with Iteration wise')
Result = array2table(HG); % Convert array to table for displaying
[Link](1:size(HG,2)) = variables

x0=x0-rem(x0,10^-n); % Convert to n decimal places

fprintf('Converged solution after %d iterations \n',iter);


fprintf('Root is %2.9f \n',x0) % Final root print
Result:

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 23
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
Program 5
ORDINARY DIFFERENTIAL EQUATIONS
MATLAB Program to solve ordinary differential equations (ODE’s) using Euler’s Method
Aim: Understand and implementation of a Euler’s Method using MATLAB.
Using Euler’s method, find the value of y(0.1) with step size h = 0.025 for differential equation

with y(0) = 1

format short % Display results in 4th decimal


clear all; % Clear all the stored variable;
clc % Clear the screen

% Define the objective function


f= @(x,y)(y-x)./(y+x)
% Input the parameters
x = input('Enter the initial value of x: ');
y = input('Enter the initial value of y(x): ');
h = input('Enter the step size (h): ');
X = input ('Enter X at which Y is required: ');

Variables = {'x','y','fxy','newy'};
k =1; % Set iteration counter
while X>=x
fprintf('Value of y at x = %f is %f \n',x,y);
fxy = f(x,y); % Compute f(x,y)
newy = y+h.*fxy; % Compute newy
rsl (k,:) = [x y fxy newy];
k = k+1; % Update iteration
x = x+h; % Update x
y = newy; % Update y
end
% Printing Optimmal results
fprintf ('Output of y(%f) = %f \n', X, rsl(end,2));

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 24
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
Results:

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 25
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
MATLAB Program to solve ordinary differential equations (ODE’s) using ode45 algorithm in
single variable
Aim: Understand and implementation of ode45 algorithm in single variable using MATLAB.
Solve the below expression using ode45 algorithm

x = [0,3], y(0) = 1, and plot y vs x.

format short
clc;
clear all;
F=@(x,y) (-2.*x.^3+x-y);
[x,y] = ode45(F,[0 3],1);
plot (x,y)
xlabel('x')
ylabel('y')
title ('ode45 to solve ODE')
Result:

ode45 to solve ODE


5

-5

-10
y

-15

-20

-25
0 0.5 1 1.5 2 2.5 3
x

MAHESH
Department of Mechanical Engineering, Rajeev P Kof Technology, HASSAN
Institute
30.05.2024 16:13 26
Digitally Signed by
Principal
RAJEEV INSTITUTE OF TECHNOLOGY, HASSAN
Plot 1-D, Growth Center, Industrial Area, B-M Bypass Road,
Hassan - 573201, Hassan, Karnataka, India.

DEPARTMENT OF ELECTRONICS AND


COMMUNICATION ENGINEERING
DSP LAB MANUAL - 21EC42

Prepared By
Mr. Ravi L.S B.E,. [Link],. (PhD)
Assistant Professor
Department of Electronics and Communication
Engineering

MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
B. E. (EC / TC)
Choice Based Credit System (CBCS) and Outcome Based Education (OBE)
SEMESTER –IV
DIGITAL SIGNAL PROCESSING LABORATORY
Course Code 21EC42 IA Marks 40
Number of Lecture 02Hr Tutorial (Instructions) + 02 Exam marks 60
Hours/Week Hours Laboratory
RBT Level L1, L2, L3 Exam Hours 03
CREDITS–02
Course Learning Objectives: This course will enable students to
 Simulate discrete time signals and verification of sampling theorem.
 Compute the DFT for a discrete signal and verification of its properties using MATLAB.
 Find solution to the difference equations and computation of convolution and correlation
along with the verification of properties.
 Compute and display the filtering operations and compare with the theoretical values.
 Implement the DSP computations on DSP hardware and verify the result.
Laboratory Experiments
Following Experiments to be done using MATLAB / SCILAB / OCTAVE or equivalent:
1. Verification of sampling theorem (use interpolation function).
2. Linear and circular convolution of two given sequences, Commutative, distributive and
associative property of convolution.
3. Auto and cross correlation of two sequences and verification of their properties
4. Solving a given difference equation.
5. Computation of N point DFT of a given sequence and to plot magnitude and phase spectrum
(using DFT equation and verify it by built-in routine).
6. (i) Verification of DFT properties (like Linearity and Parseval’s theorem, etc.) (ii) DFT
computation of square pulse and Sinc function etc.
7. Design and implementation of Low pass and High pass FIR filter to meet the desired
specifications (using different window techniques) and test the filter with an audio file. Plot the
spectrum of audio signal before and after filtering.
8. Design and implementation of a digital IIR filter (Low pass and High pass) to meet given
specifications and test with an audio file. Plot the spectrum of audio signal before and after
filtering.
Following Experiments to be done using DSP kit
9. Obtain the Linear convolution of two sequences.
10. Compute Circular convolution of two sequences.
11. Compute the N-point DFT of a given sequence.
12. Determine the Impulse response of first order and second order system.
13. Generation of Sine wave and standard test signals
Course Outcomes: On the completion of this laboratory course, the students will be able to:
• Understand the concepts of analog to digital conversion of signals and frequency domain
sampling of signals.
• Modeling of discrete time signals and systems and verification of its properties and results.
• Implementation of discrete computations using DSP processor and verify the results.
• Realize the digital filters using a simulation tool and analyze the response of the filter for an
audio signal.
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Conduct of Practical Examination:
1. All laboratory experiments are to be included for practical examination.
2. Strictly follow the instructions as printed on the cover page of answer script for breakup of
marks.
3. Change of experiment is allowed only once and Marks allotted to the procedure part to be
made zero.
Reference Books:
1. Vinay K Ingle, John G Proakis, Digital Signal Processing using MATLAB, Fourth Edition,
Cengage India Private Limited, 2017.

MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Contents
[Link] Name of the Experiment Page no
PART A : EXPERIMENTS USING SCILAB
1 Verification of sampling theorem 3
2 Linear and circular convolution of two given sequences, Commutative, 6
distributive and associative property of convolution
3 Auto and cross correlation of two sequences and verification of their 14
properties
4 Solving a given difference equation 20
5 Computation of N point DFT of a given sequence and to plot magnitude and 25
phase spectrum (using DFT equation and verify it by built-in routine)
6 Verification of DFT properties (like Linearity and Parseval’s theorem, etc.) 30
(ii) DFT computation of square pulse and Sinc function etc.
7 Design and implementation of Low pass and High pass FIR filter to meet the 35
desired specifications (using different window techniques) and test the filter
with an audio file. Plot the spectrum of audio signal before and after filtering.
8 Design and implementation of a digital IIR filter (Low pass and High pass) to 38
meet given specifications and test with an audio file. Plot the spectrum of
audio signal before and after filtering.
PART B : EXPERIMENTS USING DSP PROCESSOR
9 Obtain the Linear convolution of two sequences 52
10 Compute Circular convolution of two sequences 54
11 Compute the N-point DFT of a given sequence 57
12 Determine the Impulse response of first order and second order system 59
13 Generation of Sine wave and standard test signals 62

MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
PART A
EXPERIMENTS USING
SCILAB

MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

INTRODUCTION TO SCILAB
Overview:
SCILAB is a freely distributed and open source scientific software package. A powerful open
computing environment for Engineering and Scientific applications. Developed since 1990
by researchers from INRIA 2 (Institut Nationale de Recherche en Informatique et en
Automatique) and ENPC (National School of Bridges and Roads). Now maintained and
developed by Scilab consortium since 2003. Since 1994 it is distributed freely along with
source code through the Internet. ([Link]). Scilab users can develop their own
module so that they can solve their particular problems. The Scilab language allows to
dynamically compile and link other languages such as Fortran and C: this way, external
libraries can be used as if they were a part of Scilab built-in features. Scilab also interfaces
LabVIEW, a platform and development environment for a visual programming language
from National Instruments.
Scilab’s Main Features:
 A high-level programming language
 Scilab is an interpreted language
 Integarated object-oriented 2-D and 3-D graphics with animation
 A dedicated Editor
 An XML-based help system
 Interface with symbolic computing packages (Maple and MuPAD 3.0)
 An interface with Tcl/Tk
 Scilab works with most Unix systems including GNU/Linux and on Windows
(9X/NT/2000/XP/Vista/7), and Mac operating system
Scilab coded Toolboxes:
 Linear algebra and Sparse matrices
 Polynomials and Rational functions
 2-D and 3-D graphics with animation
 Interpolation and Approximations

Prepared by: Mr. Ravi L.S Page 1


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

 Linear, Quadratic and Nonlinear Optimization


 ODE solver and DAE solver
 Classical and Robust Control, LMI Optimization
 Differentiable and Non-differential Optimization
 Signal Processing
 Statistic
 Scicos: A hybrid dynamic system modeler and simulator
 Parallel Scialab using PVM
 Metanet: Graphs and Networks
Typical uses:
 Educational Institutes, Research centers and companies
 Math and computation
 Algorithm development
 Modeling, simulation, and visualization
 Scientific and engineering graphics, exported to various formats so that can be
included into documents.
 Application development, including GUI building
Workspace in Scilab:
 The useful workspace in Scilab consists of several windows:
 The console for making calculations
 The editor for writing programs
 The graphics windows for displaying graphics
 The embedded help

Prepared by: Mr. Ravi L.S Page 2


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

EXPERIMENT-1
VERIFICATION OF SAMPLING THEOREM
Aim: To verify sampling theorem for a signal of given frequency.
Theory:
Sampling is a process of converting a continuous time signal (analog signal) x(t) into a
discrete time signal x[n]. Converting back x[n] into analog (resulting in x(t) ) is the process of
reconstruction. Techniques for reconstruction-
 ZOH (zero order hold) interpolation results in a staircase waveform
 FOH (first order hold) where the adjacent samples are joined by straight lines
 Spline interpolation, etc.
For x(t) to be exactly the same as x(t), sampling theorem in the generation of x(n) from x(t).
The sampling frequency fs determine the spacing between [Link] theorem states
that “A band limited signal can be reconstructed exactly if it is sampled at a rate at least twice
the maximum frequency component in it”
or in mathematical terms:
fs=1/T ≥ 2 *fm
where, fs is the sampling frequency
fm is the highest frequency contained in the signal.
T is the sampling interval
Aliasing arises when a signal is discretely sampled at a rate that is insufficient to capture
the changes in the signal. It’s a process in which a high frequency signal is converted to a
lower frequency, results due to under sampling. Though it is undesirable in ADCs, it finds
practical applications in stroboscope and sampling oscilloscopes.
Scilab Program
clc;
clear;
close;
fm=100;//Enter the input signal frequency =100
k=4;//Enter the number of Cycles of input signal=4
Prepared by: Mr. Ravi L.S Page 3
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

A=1;//Enter the amplitude of input signal :


tm=0:1/(fm*fm):k/fm;
x=A*cos(2*%pi*fm*tm);
subplot(4,1,1);
plot(tm,x);
title('ORIGINAL SIGNAL');
xlabel('Time');
ylabel('Amplitude');
xgrid(1)
fnyq=2*fm;
//under sampling
fs=(3/4)*fnyq;
n=0:1/fs:k/fm;
xn=A*cos(2*%pi*fm*n);
subplot(4,1,2);
plot2d3(n,xn);
plot(n,xn,'r');
title('UnderSampling');
xlabel('Time');
ylabel('Amplitude');
legend('Sampled Signal','Reconstructed Signal');
xgrid(1)
//Nquist sampling
fs=fnyq;
n=0:1/fs:k/fm;
xn=A*cos(2*%pi*fm*n);
subplot(4,1,3),plot2d3(n,xn);
plot(n,xn,'r');
title('Nyquist Sampling');

Prepared by: Mr. Ravi L.S Page 4


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

xlabel('Time');
ylabel('Amplitude');
legend('Sampled Signal','Reconstructed Signal');
xgrid(1)
//over sampling
fs=fnyq*10;
n=0:1/fs:k/fm;
xn=A*cos(2*%pi*fm*n);
subplot(4,1,4)
plot2d3(n,xn);
plot(n,xn,'r');
title('Over Sampling');
xlabel('Time');
ylabel('Amplitude');
legend('Sampled Signal','Reconstructed Signal');
xgrid(1)
Result:

Figure: Output Plot.


Prepared by: Mr. Ravi L.S Page 5
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

EXPERIMENT-2
LINEAR AND CIRCULAR CONVOLUTION OF TWO GIVEN
SEQUENCES, COMMUTATIVE, DISTRIBUTIVEAND
ASSOCIATIVE PROPERTY OF CONVOLUTION.

Aim: To obtain the linear, circular convolutions of two given sequences and verify
Commutative, Distributive and Associative Properties of Convolution.
Theory:
Linear convolution:
The mathematical definition of linear convolution in discrete time domain

Where x(n) is input signal, h(n) is impulse response, and y(n) is output.*denotes
convolution. Here we multiply the terms of x(k) by the terms of a time-shifted h(n) and add
them up. The output length of y(n) =length[x(n)]+length[h(n)]-1.
Circular convolution:
Circular convolution of two discrete time sequences x(n) and h(n) each of length N gives
another sequence y(n) of length [Link] is given by

The output length of y(n) =max(length[x(n)],length[h(n)]).


Properties of convolution:
 Commutative property
x(n)*h(n)=h(n)*x(n)
 Distributive property
x(n)*{h1(n)+h2(n)}=x(n)*h1(n)+x(n)*h2(n)
 Associative property

Prepared by: Mr. Ravi L.S Page 6


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

x(n)*{h1(n)*h2(n)}={x(n)*h1(n)}*h2(n)
Scilab Program for Linear convolution:
clc;
clear;
close;
x=input('enter the 1st sequence');
h=input('enter the 2nd sequence');
xr=input('enter the range of 1st sequence');
hr=input('enter the range of 2nd sequence');
y=conv(x,h);
disp('linear convolution of two given sequences is');
disp(y);
xr1=xr(1):xr(2);
hr1=hr(1):hr(2);
yr1=xr1(1)+hr(1):xr(2)+hr(2);
subplot(3,1,1);
plot2d3(xr1,x);
xlabel('time index n');
ylabel('amplitude');
title('plot of x');
subplot(3,1,2);
plot2d3(hr1,h);
xlabel('time index n');
ylabel('amplitude');
title('plot of h');
subplot(3,1,3);
plot2d3(yr1,y);
xlabel('time index n');
ylabel('amplitude');

Prepared by: Mr. Ravi L.S Page 7


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

title('Linear convolution output');


Result:
enter the 1st sequence [1 2 3 4]
enter the 2nd sequence [2 1 2 1]
enter the range of 1st sequence [0 3]
enter the range of 2nd sequence [0 3]
"linear convolution of two given sequences is" 2. 5. 10. 16. 12. 11. 4.

Figure: Output plot of Linear convolution plot(right sided sequences).

enter the 1st sequence[1 2 3 4]


enter the 2nd sequence[2 1 2 1]
enter the range of 1st sequence[-1 2]
enter the range of 2nd sequence[-2 1]
"linear convolution of two given sequences is" 2. 5. 10. 16. 12. 11. 4.

Prepared by: Mr. Ravi L.S Page 8


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

Figure: Output plot of linear convolution plot (two sided sequences).

Scilab Program for Circular convolution:


clc;
clear;
close;
x=input('enter the 1st sequence');
h=input('enter the 2nd sequence');
N1=length(x);
N2=length(h);
N=max(N1,N2);
N3=N1-N2;
if(N1>N2)
h=[h,zeros(1,N3)];
else if(N2>N1)
x=[x,zeros(1,-N3)];
end

Prepared by: Mr. Ravi L.S Page 9


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

end
for m=1:N
y(m)=0;
for n=1:N
i=m-n+1;
if(i<=0)
i=N+i;
end
y(m)=y(m)+x(n)*h(i);
end
end
disp('circular convolution of two given sequence is');
disp(y);
n1=0:N-1;
subplot(3,1,1);
plot2d3(n1,x);
xlabel('time index n');
ylabel('amplitude');
title('plot of x');
subplot(3,1,2);
plot2d3(n1,h);
xlabel('time index n');
ylabel('amplitude');
title('plot of h');
subplot(3,1,3);
plot2d3(n1,y);
xlabel('time index n');
ylabel('amplitude');
title('circular convolution output');

Prepared by: Mr. Ravi L.S Page 10


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

Result:
enter the 1st sequence[0 1 2 3]
enter the 2nd sequence[0 3 3 3]
“circular convolution of two given sequence is”18. 15. 12. 9

Figure: output plot of circular convolution.

Scilab Program for Properties of convolution:


clc;
clear;
close;
a=input('enter the a sequence');
b=input('enter the b sequence');
c=input('enter the c sequence');

Prepared by: Mr. Ravi L.S Page 11


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

//properties of convolution
//commutative property a*b=b*a
c1=conv(a,b);
c2=conv(b,a);
if(c1==c2)
disp('commutative property is proved');
disp('c1=');
disp(c1);
disp('c2=');
disp(c2);
end
//associative property [a*(b*c)=(a*b)*c]
a1=conv(a,conv(b,c));
a2=conv(conv(a,b),c);
if(a1==a2)
disp('associative property is proved ');
disp('a1=');
disp(a1);
disp('a2=');
disp(a2);
end
//distributive property [a*(b+c)=(a*b)+(a*c)]
d1=conv(a,b+c);
d2=conv(a,b)+conv(a,c);
if(d1==d2)
disp('distributive property is proved');
disp('d1=');
disp(d1);
disp('d2=');

Prepared by: Mr. Ravi L.S Page 12


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

disp(d2);
end
Result of Properties of convolution:
"commutative property is proved"
"c1=" 2. 5. 10. 16. 12. 11. 4.
"c2=" 2. 5. 10. 16. 12. 11. 4.
"associative property is proved "
"a1="2. 7. 17. 33. 43. 49. 43. 27. 15. 4.
"a2="2. 7. 17. 33. 43. 49. 43. 27. 15. 4.
"distributive property is proved"
"d1="3. 8. 16. 26. 21. 18. 8.
"d2=" 3. 8. 16. 26. 21. 18. 8.

Prepared by: Mr. Ravi L.S Page 13


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

EXPERIMENT-3
AUTO AND CROSS CORRELATION OF TWO SEQUENCES
AND VERIFICATION OF THEIR PROPERTIES
Aim: To obtain the Auto and cross correlation of two sequences and verification of their
properties.
Theory:
Correlation determines the degree of similarity between two signals. If the signals are
identical, then the correlation is 1; if they are totally different, the correlation coefficient is 0,
an if they are identical except that the phase is shifted by exactly 1800(i.e mirrored), then the
correlation coefficient is -[Link] are two types of correlation
Autocorrelation-The Autocorrelation of a sequence is correlation of a sequence with itself.
The autocorrelation of a sequence x(n) is defined by

Where k is the shift parameter

Properties of autocorrelation

 Autocorrelation sequence is symmetric i.e

Rxx(k)=Rxx(-k)

 Autocorrelation function at k=0, is equal to max value (greatest element)

 Autocorrelation function at k=0, is equal to mean square value i.e

Cross correlation –when two independent signals are compared ,the procedure is known as
cross-correlation .it is given by,

Prepared by: Mr. Ravi L.S Page 14


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

Where k is the shift parameter

Properties of Cross-correlation

 Reflection property

i. eRxy(-k)=Ryx(k)

 Greatest element

|Rxy(k)|2≤Rxx(0) Ryy(0)

Scilab Program for autocorrelation:


clc;
clear;
close;
x=input('enter the sequence');
N=length(x);
rxx=xcorr(x);
disp('auto correlation sequence is');
disp(rxx);
//symmetry property
if(rxx==flipdim(rxx,2))
disp('rxx sequence is symmetric');
else
disp('rxx sequence is not symmetric');
end
//energy property
e=sum(x.^2)
if(e==rxx(N))
disp('energy property is proved');

Prepared by: Mr. Ravi L.S Page 15


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual
else
disp('energy property is not proved');
end
//rxx(0) is greater value
for i=1:N-1
if(rxx(N)>rxx(i))
p=1;
else
p=0;
break;
end
end
if(p==1)
disp('rxx(0) is greatest element');
else
disp('rxx(0)is not the greatest element');
end
n=0:N-1;
subplot(2,1,1);
plot2d3(n,x);
title('input sequence');
n1=-(N-1):(N-1);
subplot(2,1,2);
plot2d3(n1,rxx);
title('auto correlated sequence');
Result :
enter the sequence[1 2 3 4]

"auto correlation sequence is" 4. 11. 20. 30. 20. 11. 4.

Prepared by: Mr. Ravi L.S Page 16


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual
rxx sequence is symmetric"

"energy property is proved"

"rxx(0) is greatest element"

Figure: Output plot of auto correlation.


Scilab Program for Cross correlation
clc;
clear;
close
x=input('enter the sequence x=');
y=input('enter the sequence y=');
N1=length(x);
N2=length(y);
rxy=xcorr(x,y);
ryx=xcorr(y,x);
disp(rxy);
disp(ryx);
rxx=xcorr(x,x);
ryy=xcorr(y,y);
//reflection property rxy(k)=ryx(-k)
if(rxy==flipdim(ryx,2))

Prepared by: Mr. Ravi L.S Page 17


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual
disp('reflection property is proved');
else
disp('reflection property is not proved');
end
// greatest element sqrt(rxx(0)*ryy(0)>=rxy(k)
rxx0=rxx(N1);
ryy0=ryy(N2);
grst=sqrt(rxx0*ryy0);
if(grst>rxy)
p=1;
else
p=0;
end
if(p==1)
disp('greatest element');
else
disp('not greatest element');
end
n=0:N1-1;
subplot(4,1,1);
plot2d3(n,x);
title('x sequence');
subplot(4,1,2);
plot2d3(n,y);
title('y sequence');
n1=-(N1-1):(N1-1);
subplot(4,1,3);
plot2d3(n1,rxy);
title('cross correlation rxy sequence');

subplot(4,1,4);
Prepared by: Mr. Ravi L.S Page 18
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual
plot2d3(n1,ryx);
title('cross correlation ryx sequence');
Result: enter the sequence x=[1 2 3 4]
enter the sequence y=[1 1 1 1]

1. 3. 6. 10. 9. 7. 4.

4. 7. 9. 10. 6. 3. 1.

"reflection property is proved"

"greatest element"

Figure: Output plot of cross correlation.

Prepared by: Mr. Ravi L.S Page 19


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

EXPERIMENT-4
SOLVING A GIVEN DIFFERENCE EQUATION
Aim: To obtain the response of a system described by the given difference equation.
Theory:
This is another type of time domain representation for LTI system. It gives the relationship
between the input and output of LTI system. Differential equations are used to represent
continuous time systems whereas difference equations are used to represent discrete time
system.
The general form of a linear constant coefficients difference equation is given by

Where x(n) is input to the system


y(n) is output to the system
The solutions to the difference equation has two components
 Natural response yn(n):This is the response of the system for the Zero input that is
by making x(n)=[Link] is called as zero input response
Thus equation (1) becomes

 Forced response yf(n):This is the response due to input x(n) only and here the initial
conditions are assumed to be zeroes. Forced response is also called as zero state
response.
 Total response yT(n): To find the total response of the LTI system described by the
difference equation, we have to consider both the initial condition as well as input.
Total response is given by the sum of natural response and forced response that is

yT(n)=yf(n)+yn(n)

Prepared by: Mr. Ravi L.S Page 20


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

Scilab program:
clc;
clear;
close;
N=input('enter numerator co-efficients');
D=input('enter denominator co-efficients');
L=input('enter the length');
x=[1,zeros(1,L-1)];
h=filter(N,D,x);
disp(h);
n=0:L-1;
plot2d3(n,h);
title(' response ');
Result:
enter numerator co-efficients [5 6]

enter denominator co-efficients [1 1 -6]

enter the length 4

5. 1. 29. -23.

Prepared by: Mr. Ravi L.S Page 21


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

Figure: Output plot of natural response.


enter numerator co-efficients [8]

enter denominator co-efficients [1 0 -7 6]

enter the length 4

8. 0. 56. -48.

Prepared by: Mr. Ravi L.S Page 22


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

Figure: Output plot of forced response.

enter numerator co-efficients [13 1 -6]

enter denominator co-efficients [1 0 -7 6]

enter the length4

13. 1. 85. -71.

Prepared by: Mr. Ravi L.S Page 23


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

Figure: Output plot of total response.

Prepared by: Mr. Ravi L.S Page 24


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

EXPERIMENT-5
COMPUTATION OF N POINT DFT OF A GIVEN
SEQUENCE AND TO PLOT MAGNITUDE AND PHASE
SPECTRUM (USING DFT EQUATION AND VERIFY IT BY
BUILT-IN ROUTINE)

Aim: To obtain the Discrete Fourier Transform (DFT) of a given sequence and to plot its
magnitude and phase responses.
Theory:
Discrete Fourier Transform (DFT) is used for performing frequency analysis of discrete time
signals. DFT gives a discrete frequency domain representation whereas the other transforms
are continuous in frequency domain.
The N point DFT of discrete time signal x(n) is given by the equation

Where N is chosen such that L≥N, where L=length of x(n).


X(k) is a complex number . It has both magnitude and phase which are plotted versus k.
These plots are magnitude and phase spectrum of x(n). The ‘k’ gives us the frequency
information.
Scilab Program for N-point DFT using DFT equation:
clc;
clear;
close;
x=input('enter the sequence x(n)=');//input time domain sequence
N=input('enter the length');//length of the DFT
L=length(x);
if(N>=L)
x=[x zeros(1,N-L)];

Prepared by: Mr. Ravi L.S Page 25


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

elseif(N<L)
error('length of x(n) must be less than or equal to N');
end
n=0:N-1;
k=0:N-1;
nk=n'*k;
wn=exp(-%i*2*%pi/N);
wk=wn.^nk;
xk=wk*x';
disp('DFT of given sequence is');
yk=round(xk);
disp(yk);
magnitude=abs(yk);//magnitude of frequency domain signal X(k)
disp('Magnitude Response of DFT is');
disp(magnitude);
disp('Phase Response of DFT is');
//phase=angle(xk);
phase=atan(imag(yk),real(yk));//phase of frequency signal X(k)
disp(phase);
p=0:N-1;
// Input sequence
subplot(3,1,1);
plot2d3(p,x);
xlabel('Time index n');
ylabel('Amplitude');
title('Input sequence');
//Magnitude spectrum
subplot(3,1,2);
plot2d3(p,magnitude);

Prepared by: Mr. Ravi L.S Page 26


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

xlabel('Frequency sample Index K--->');


ylabel('|X(k)|');
title('Magnitude spectrum');
//Phase spectrum
subplot(3,1,3);
plot2d3(p,phase);
xlabel('Frequency sample Index K --- >');
ylabel('<X(k) in radians');
title('Phase spectrum');

Scilab Program for N-point DFT using built-in routine:


clc;
clear;
close;
x=input('enter the sequence x(n)=');//input time domain sequence
N=input('enter the length');//length of the DFT
xk=fft(x);
disp('DFT of given sequence is');
disp(xk);
magnitude=abs(xk);//magnitude of frequency domain signal X(k)
disp('Magnitude Response of DFT is');
disp(magnitude);
disp('Phase Response of DFT is');
//phase=angle(xk);
phase=atan(imag(xk),real(xk));//phase of frequency signal X(k)
disp(phase);
p=0:N-1;
//Input sequence
subplot(3,1,1);

Prepared by: Mr. Ravi L.S Page 27


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

plot2d3(p,x);
xlabel('Time index n');
ylabel('Amplitude');
title('Input sequence');
//Magnitude spectrum
subplot(3,1,2);
plot2d3(p,magnitude);
xlabel('Frequency sample Index K--->');
ylabel('|X(k)|');
title('Magnitude spectrum');
//Phase spectrum
subplot(3,1,3);
plot2d3(p,phase);
xlabel('Frequency sample Index K --- >');
ylabel('<X(k) in radians');
title('Phase spectrum');
Result: enter the sequence x(n)=[1 2 3 4]
enter the length 4

"DFT of given sequence is"

10. + 0.i -2. + 2.i -2. + 0.i -2. - 2.i

"Magnitude Response of DFT is"

10. 2.8284271 2. 2.8284271

"Phase Response of DFT is"

0. 2.3561945 -3.1415927 -2.3561945

Prepared by: Mr. Ravi L.S Page 28


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

Figure: Output plot of magnitude and phase response.

Prepared by: Mr. Ravi L.S Page 29


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

EXPERIMENT-6

(i) Verification of DFT properties (Linearity and Parseval’s


theorem).
(ii) DFT computation of square pulse and Sinc function.

Aim: To verify following properties of DFT (Linearity and Parseval’s theorem and DFT
computation of square pulse and sinc function.
Theory:
Linearity property
If and

then

Parseval’s theorem
Let X(K) be the Discrete Fourier transform of the sequence x(n),Then we have

Scilab Program for Linearity property:


clc;
clear;
close;
x1=input('enter the 1st sequence=');
x2=input('enter the 2nd sequence=');
a=input('enter the 1st constant a=');
b=input('enter the 2nd constant b=');
N=input('enter the length of DFT=');
term1=a.*x1+b.*x2;
Prepared by: Mr. Ravi L.S Page 30
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

LHS=fft(term1);
term2=fft(a.*x1);
term3=fft(b.*x2);
RHS=term2+term3;
if(LHS==RHS)
disp('Linear property is proved');
disp('LHS=');
disp(LHS);
disp('RHS=');
disp(RHS);
else
disp('DFT is not linear');
end
Result:
enter the 1st sequence=[1 2 3 4]

enter the 2nd sequence=[3 1 1 3]

enter the 1st constant a=1

enter the 2nd constant b=1

enter the length of DFT=4

"Linear property is proved"

"LHS="18. + 0.i 0. + 4.i -2. + 0.i 0. - 4.i

"RHS="18. + 0.i 0. + 4.i -2. + 0.i 0. - 4.i

Scilab Program for parseval's theorem:


clc;
clear;
close;
x=input('enter the sequence');

Prepared by: Mr. Ravi L.S Page 31


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

N=input('enter the length');


y=fft(x);
E1=sum(x.^2);
E2=(1/N)*sum(abs(y).^2);
if (E1==E2)
disp('Energy=');
disp(E1);
disp(E2);
disp('parseval theorem proved');
else
disp('parseval theorem not proved');
end
Result:
enter the sequence[1 2 3 4]

enter the length4

"Energy="

E1=30.

E2=30.

"parseval theorem proved"

Scilab Program for square pulse:


clc;
close;
clear;
x=[zeros(1,32),ones(1,64),zeros(1,32)];
xk=fft(x);
xk1=fftshift(xk);
subplot(2,1,1);

Prepared by: Mr. Ravi L.S Page 32


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

plot2d3(x);
title('time domain');
subplot(2,1,2);
plot(abs(xk1));
title('frequency domain');
Result:

Figure: Output Plot.


Scilab Program for sinc function:
clc;
clear;
close;
x= -2:0.05:2;

Prepared by: Mr. Ravi L.S Page 33


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

x1=sinc(2*%pi*x);
xk=fft(x1);
xk1=fftshift(xk);
subplot(2,1,1);
plot2d3(x1);
title('time domain');
subplot(2,1,2);
plot(abs(xk1));
title('frequency domain');
Result:

Figure: Output Plot.

Prepared by: Mr. Ravi L.S Page 34


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

EXPERIMENT-7
DESIGN AND IMPLEMENTATION OF FIR FILTER TO
MEET THE DESIRED SPECIFICATIONS
AIM: To design and implement a FIR filter for given specifications.

THEORY: A FIR filter has finite number of samples in its impulse response. The FIR filters
are of non-recursive type, whereby the present output sample is depending on the present
input sample and previous input samples.
The Design Procedure of FIR filters using windows method.
Step 1: Select the desired frequency response of the filter

Step 2: Find the desired unit impulse response hd(n) from the desired frequency response
Hd(ejw) by obtaining the inverse Fourier transform using the equation

Step 3: Since hd(n) is an infinite sequence, truncate it to get a finite sequence of length N,say
from n=0 to N-1
i.e h(n)=hd(n)* w(n)
Where w(n) is a “window sequence”
Step 4: By taking Z-transform of h(n),obtain the Transfer function H(z) of the filter
Step 5: Obtain the frequency response i.e magnitude response and phase response

Table: Summary of important features of window functions

Prepared by: Mr. Ravi L.S Page 35


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

Name of window Transition Stopband attenuation Window function


function width (dB) minimum

Rectangular 21 1

Bartlett 25

Hanning 44

Hamming 53

Scilab program:

// Designing FIR Low pass filter:


clc
clear
close
N=11;// if you change order, you can notice changes in spectrum
fs=16000;// since speech signal is 16000
alpha=(N-1)/2
wc=0.125*%pi;// take cutoff frequency as 1k (0.125 * fs/2 = 1000)
win_hm=window('re',N)// by changing different windows, yo can notice changes in spectrum
for n=0:N-1
hd(n+1)=sin(wc*(n-alpha))/(%pi*(n-alpha));
if n==alpha
hd(n+1)=wc/%pi
end
end
h=hd.*win_hm';
disp('Impulse response h(n) of a filter specification is',h')

Prepared by: Mr. Ravi L.S Page 36


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

[x,fs]=wavread('C:\Users\ECNAVKIS\Downloads\speech_sample.wav')// read wave file


playsnd(x,fs)// play audio signal before filtering
sleep(3,'s')// pause for 3sec to avoid overplaying second file after filtering
X=fft(x);
figure(1)
subplot(211)
plot(abs(X)/(fs/2))//plot of spectrum of audio signal before filtering
xlabel('samples');
ylabel('amplitude');
title('spectrum of audio signal before filtering');
y=conv(x,h)
playsnd(y,fs)// play audio signal after filtering notice the changes in the audio signal
Y=fft(y)
subplot(212)
plot(abs(Y)/(fs/2))//plot of spectrum of audio signal after filtering
xlabel('samples');
ylabel('amplitude');
title('spectrum of audio signal after filtering');
Result:

Figure: Output Plot.


Prepared by: Mr. Ravi L.S Page 37
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

EXPERIMENT-8

DESIGN AND IMPLEMENTATION OF IIR FILTER TO


MEET THE DESIRED SPECIFICATIONS
AIM: To design and implement an IIR filter for given specifications.

THEORY: A digital IIR(Infinite Impulse Response ) filter is a linear time invariant discrete
time systems which has infinite duration impulse response h(n).IIR filters are recursive i.e
the present output sample depends on the present and /or past input and past output samples.
The design of a digital IIR filter involves the design of the filter in the analog domain and
then transforms it into the digital domain using various analog to digital transformation
methods.
The different steps involved in the design of a digital IIR filter are,
(i) The frequency response specification in digital domain is converted into analog and an
equivalent analog filter Ha(s) is designed by using any one of the approximation techniques
like Butterworth, chebyshev etc.
(ii) The analog transfer function Ha(s) is converted to digital transfer function H(z) using
various analog to digital transformation methods like Impulse invariance, Bilinear
transformation, backward difference, matched Z-transform etc
Scilab program:

//Designing iir filter using butterworth approximation


clc
clear
close
[x,fs]=wavread('C:\Users\ECNAVKIS\Downloads\speech_sample.wav');//read speech
playsnd(x,fs)// play audio signal before filtering
sleep(3,'s')// pause for 3sec to avoid overplaying second file after filtering
X=fft(x);

Prepared by: Mr. Ravi L.S Page 38


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept. of ECE, RIT, Hassan DSP Lab Manual

figure(1)
subplot(211)
plot(abs(X)/(fs/2))// plot spectrum signal of Before Filtering
xlabel('samples');
ylabel('amplitude');
title('spectrum of audio signal before filtering');
hz=iir(3,'lp','butt',[0.125 0],[0 0]);// lowpass filter with cutoff frequency as 1000 hz
y=flts(x,hz);//apply the input signal to filter coefficients
playsnd(y,fs)// play audio signal after filtering notice the changes in the audio signal
Y=fft(y)
subplot(212)
plot(abs(Y)/(fs/2))
xlabel('samples');
ylabel('amplitude');
title('spectrum of audio signal after filtering');
Result:

Figure: Output Plot.

Prepared by: Mr. Ravi L.S Page 39


MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
PART B
EXPERIMENTS USING
DSP PROCESSOR

MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

INTRODUCTION TO CODE COMPOSER STUDIO


Code Composer Studio v4 (CCStudio v3.3) is the integrated development environment
(IDE) for TI's DSPs, microcontrollers and application processors. Code Composer Studio
IDE includes a suite of tools used to develop and debug embedded applications. It includes
compilers for each of TI's device families, source code editor, project build environment,
debugger, profiler, simulators and many other features. The CCStudio IDE provides a single
user interface taking you through each step of the application development flow. Familiar
tools and interfaces allow users to get started faster than ever before and add functionality to
their application thanks to sophisticated productivity tools.
Introduction of main board:
 USB2.0 CY7C68013-56PVC, compatible with USB2.0 and USB1.1, including 8051

 DSP TMS320C6713 TQFP-208 Package Device with, 4 layers board


 SDRAM MT48LC4M16A2 1meg*16 *4 bank micron
 FLASH AM29LV800B 8Mbit1Mbyte of AMD
 RESET chip specialize for reset with button for manually reset
 POWER supply externally, special 5V, 3.3V, 1.6V chip for
steady voltage with remaining for other devices.
 EEPROM 24LC64 for download of USB firmware
 CPLD XC95144XL
 AIC TLV320AIC23B sampling with 8-96KHZ, 4 channels with interface of
headphone.

Figure: Main Board


MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 40
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

The setup of USB Programmer and emulator in CCS v3.3

1. The setup of USB Programmer and emulator in CCS v3.3


2. Install USB Emulator chooses to install directory from CCS v3.3 hat is if
CCSv3.3 is installed in C: / CCStudio_v3.3 directory, then install the USB emulator
driver in this directory.

Procedure to Setup Emulator:


3. Open the “Setup CCStudio v3.3”

4. Choose c67xx in the “Family”.

5. Choose AHxds510usb emulator in the “Platform”.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 41
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

6. Choose little in the “Endianness”.

7. Now you are left with two options under Available Factor Boards, Choose C671X
AHXDS510 USB Emulator, right click and “Add to system...”

8. Now the Emulator and the processor both are selected under “system configuration”.

9. Choose file and click on “save”.


10. Choose file and click on “exit” you will get a wizard as shown bellow.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 42
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

Click on yes. Then it launches a Code Composer Studio

11. Connect the power supply to the board (5V, 3A): make sure that supply is there in
the board by pressing reset button.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 43
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
12. After 2 minutes after power supply is turned on then connects the USB Programmer
cable to DSP JTAG connector and Host Computer where CCS 3.3 is installed.

13. Go to Debug and select the Reset Emulator.

14. Go to Debug and select the option connect by Pressing Reset Button on the board.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 44
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

15. Now Target is connected.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 45
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
16. Go to Debug and press Reset CPU that will initialize your memory.

Now Board is ready for working real and non-real time programs.

Procedure to create new Project:


1. To create project, Go to Project and Select New.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 46
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
2. Give project name and click on finish.

(Note: Location must be c:\CCStudio_v3.3\MyProjects).


3. Click on File---- New ---- Source File, To write the Source Code.

4. Write the program and save the file with “.C” extension.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 47
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
5. Right click on source, Select add files to project and Choose “.C “file Saved before.

6. Right Click on libraries and select add files to Project and choose
C:\CCStudio_v3.3\C6000\cgtools\lib\[Link] and click open.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 48
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
7. a) Go to Project to Compile.

b) Go to Project to Build.

c) Go to Project to Rebuild All.

8. Go to file and load program and load “.out” file into the board.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 49
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
9. Go to Debug and click on run to run the program.

10. Observe the output in output window.

11. To see the Graph go to View and select time/frequency in the Graph, and give the

Correct Start address provided in the program, Display data can be taken as per user.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 50
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

12. Green line is to choose the point, Value at the point can be seen (Highlighted by
circle at the left corner).

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 51
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

EXPERIMENT-9

OBTAIN THE LINEAR CONVOLUTION OF TWO


SEQUENCES
Aim: To perform linear convolution for the given sequences.

Theory:
The mathematical definition of linear convolution in discrete time domain

Where x(n) is input signal, h(n) is impulse response, and y(n) is output.*denotes
convolution. Here we multiply the terms of x(k) by the terms of a time-shifted h(n) and add
them up. The output length of y(n) =length[x(n)]+length[h(n)]-1.

C Program:
#include<stdio.h>
int m=4; /*Length of i/p samples sequence*/
int n=4; /*Length of impulse response Co-efficients */
int i=0,j=0;
int x[10]={1,2,3,4}; /*Input Signal Samples*/
int h[10]={1,2,3,4}; /*Impulse Response Co-efficients*/
int y[10];
void main()
{
for(i=0; i<m+n-1; i++)
{
y[i]=0;
for(j=0; j<=i; j++)
y[i]+=x[j] * h[i-j]; /* y[i]=y[i]+x[j] * h[i-j]; */
}
for(i=0; i<m+n-1; i++)
printf("%d\n ",y[i]);
}
MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 52
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

Output:
1, 4, 10, 20, 25, 24, 16.

Figure: Plot of output sequence.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 53
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

EXPERIMENT-10

CIRCULAR CONVOLUTION OF TWO GIVEN SEQUENCES


Aim: To perform circular convolution of two given sequences

Theory:
Circular convolution of two discrete time sequences x(n) and h(n) each of length N gives
another sequence y(n) of length [Link] is given by

The output length of y(n) =max(length[x(n)],length[h(n)]).

C program:
#include<stdio.h>
#include<math.h>
int x[4]={1,2,3,4}; /*Input Signal Samples*/
int h[4]={1,2,2,1}; /*Impulse Response Co-efficients*/
int m=4; /*maximum Length of two i/p sequence*/
int y[4];
int k=0,n=0,i=0;
void main()
{
Printf(“the circular convolution is \n”);
for (n=0; n<m; n++)
{
y[n]=0;
for (k=0; k<m; k++)
{
i=(n-k) %m;
if (i<0)
i=i+m;

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 54
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
y[n]+=h[k]*x[i]; /* y[n]=y[n]+h[k]*x[i];*/
}
Printf(“%d\n”,y[n]);
}
}

Output:
17 15 13 15

Figure: Plot of output sequence.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 55
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

EXPERIMENT-11

COMPUTATION OF N- POINT DFT OF A GIVEN


SEQUENCE
Aim: To compute the N (=4/8/16) point DFT of the given sequence

Theory:
Discrete Fourier Transform (DFT) is used for performing frequency analysis of discrete time
signals. DFT gives a discrete frequency domain representation whereas the other transforms
are continuous in frequency domain.
The N point DFT of discrete time signal x(n) is given by the equation

Where N is chosen such that L≥N, where L=length of x(n).


C program:

#include <stdio.h>
#include <math.h>
Main ()
{
float y[16]; /*for 8 point DFT to store real & imaginary*/
float x[4]={1,2,3,4}; /*input only real sequence */
float w;
int n,k,k1,N=4,xlen=4;
for(k=0; k<2*N; k=k+2)
{
y[k]=0;
y[k+1]=0; /*initialize real & imaginary parts */
k1=k/2; /*actual k index*/
for(n=0; n<xlen; n++)
{
w= -2*3.14159265359*k1*n/N; /*careful about minus sign*/
MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 56
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
y[k]=y[k]+x[n]*cos(w);
y[k+1]=y[k+1]+x[n]*sin(w);
}
printf("%f+j%f \n",y[k],y[k+1]);
}
}

Output:
Y[k]=10, -2+j2, -2-0j, -2-j2

Figure: Plot of output sequence.

Note: Use [Link] Library function to get floating point output.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 57
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

EXPERIMENT-12

DETERMINE THE IMPULSE RESPONSE OF FIRST ORDER


AND SECOND ORDER SYSTEM
Aim: To find the Impulse response of the given first order / second order system

Theory:

Figure. A LTI system

A discrete time LTI system (also called digital filters) as shown in Figure is represented by
A linear constant coefficient difference equation, for example
y[n]  a1 y[n 1]  a2 y[n  2]  b0 x[n]  b1 x[n 1]  b2 x[n  2];
A system function H(z) (obtained by applying Z transform to the difference equation).
Y (z) b  b z 1  b z 2
H (z)   0 1 2
X (z) 1  a 1 z 1  a 2 z 2
We can find the impulse function h[n] by using the inverse z-transform.
C program:

#include<stdio.h>
#define Order 3 /* Order of difference equation*/
#define Len 5 /* length of impulse response sequence */
float h[Len] = {0.0,0.0,0.0,0.0,0.0},sum;
void main()
{
int j,k;
float a[Order+1] = {0.8,-0.44,0.36,0.02}; /* Numerator coefficients */
float b[Order+1] = {1,0.7,-0.44,-0.6}; /* Denominator coefficients */
printf("Impulse response of the given system:\n");

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 58
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
for(j=0;j<Len;j++)
{
sum = 0.0;
for(k=1;k<=Order;k++)
{
if((j-k)>=0)
sum = sum+(b[k]*h[j-k]);
}
if(j<=Order)
{
h[j] = a[j]-sum;
}
else
{
h[j] = -sum;
}
printf("%f",h[j]);
}
}

Result:

h(n)= {0.8, -1.00, 1.412, -09284, 0.671

Note: Use [Link] Library function to get floating point output.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 59
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
EXPERIMENT-12

GENERATION OF SINE WAVE AND STANDARD TEST


SIGNALS
Aim: Generation of Sine wave and standard test signals
Theory:
Sinusoidal Wave
The sine wave or sinusoidal wave is a mathematical curve that describes smooth repetitive
oscillations. It can be represented in mathematical form as

where A=Amplitude in V
ω=angular frequency
ϕ=Phase in radians.
Square Wave
The square wave is a non-sinusoidal periodic wave form which is represented as infinite
summation of sinusoidal waves in which the amplitude alternates at a steady frequency
between fixed minimum and maximum values with the same duration at maximum and
minimum.
C program:
Sine wave
# include <stdio.h>
# include <math.h>
float a[100];
void main()
{
int i;
for(i=0;i<99;i++)
{
a[i] =sin(2*3.14*5*i/100);
printf("%f" ,a[i]);

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 60
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
} }
Cos wave
# include <stdio.h>
# include <math.h>
float a[100];
void main()
{
int i;
for(i=0;i<99;i++)
{
a[i] =cos(2*3.14*5*i/100);
printf("%f" ,a[i]);
}}
Square wave
# include <stdio.h>
# include <math.h>
void main()
{
int *square;
int i;
square=(int *)0x0000100;
while(1)
{
for(i=0;i<50;i++)
{
*square++=0x0000FFFF;
}
for(i=0;i<50;i++)
{
*square++=0x0;
} } }

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 61
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
Triangle wave
# include <stdio.h>
# include <math.h>
void main()
{
int *Triangle;
int i=0,j=0;
Triangle=(int *)0x0000100;
while(1)
{
for(i=0;i<50;i++)
{
j=j+1;
*Triangle++=j;
}
for(i=50;i>0;i--)
{
j=j-1;
*Triangle++=j;
} } }
Result:

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 62
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual

Figure: Output waveforms

Note: Use [Link] Library function to get the output.

MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 63
Digitally Signed by
Principal

You might also like