MATLAB Lab Manual for Mechanical Engineering
MATLAB Lab Manual for Mechanical Engineering
HASSAN-573201
DEPARTMENT OF
MECHANICAL ENGINEERING
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
RAJEEV INSTITUTE OF TECHNOLOGY
HASSAN-573201
Name:……………………………………………………….
USN:……………………………………………………..
DEPARTMENT OF
MECHANICAL ENGINEERING
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
BASICS OF MATLAB 21ME581 - LAB MANUAL ME
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
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
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.
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 2: An ability to embrace professional and ethical attitude with awareness of societal
impact
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.
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.
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
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
Syllabus iii
Contents vi
EXPERIMENTS
1. INTRODUCTION TO MATLAB 1
2. CURVE FITTING 13
3. NUMERICAL INTEGRATION 17
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
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
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
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
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 ^ .^
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.
( ) ∫
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);
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
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
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
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:
-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.
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
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
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:
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
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');
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');
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
//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=');
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.
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
Properties of autocorrelation
Rxx(k)=Rxx(-k)
Cross correlation –when two independent signals are compared ,the procedure is known as
cross-correlation .it is given by,
Properties of Cross-correlation
Reflection property
i. eRxy(-k)=Ryx(k)
Greatest element
|Rxy(k)|2≤Rxx(0) Ryy(0)
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.
"greatest element"
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
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)
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]
5. 1. 29. -23.
8. 0. 56. -48.
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
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);
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
EXPERIMENT-6
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
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]
"Energy="
E1=30.
E2=30.
plot2d3(x);
title('time domain');
subplot(2,1,2);
plot(abs(xk1));
title('frequency domain');
Result:
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:
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
Rectangular 21 1
Bartlett 25
Hanning 44
Hamming 53
Scilab program:
EXPERIMENT-8
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:
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:
MAHESH P K
30.05.2024 16:13
Digitally Signed by
Principal
Dept of ECE, R.I.T Hassan DSP Lab Manual
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
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”.
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
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.
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
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.
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.
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.
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.
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
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.
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
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
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
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
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
#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
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
Theory:
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:
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
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
MAHESH P K
Prepared by: Mr. Ravi L.S 30.05.2024 16:13 Page 63
Digitally Signed by
Principal