[go: up one dir, main page]

0% found this document useful (0 votes)
16 views73 pages

IT EM Lab Record

Sri Manakula Vinayagar Engineering College record for IT 2 nd yr students

Uploaded by

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

IT EM Lab Record

Sri Manakula Vinayagar Engineering College record for IT 2 nd yr students

Uploaded by

btechit240937
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 73

LAB MANUAL

Course Name: Engineering Mathematics Laboratory

Course Code: U23MAPC01

1
Engineering Mathematics Laboratory
Department Mathematics Programme: B.Tech.
Semester III Course Category Code: *End Semester ExamType:
CC LE
U23MAPC01 Periods/Week Credit Maximum Marks
Course Code
L T P C CAM ESE TM
Course Name Engineering Mathematics 0 0 2 1 50 50 100
Laboratory
(Common to all Branches Except CSBS)
Prerequisite Matrices, Fourier Transforms, Laplace Transforms
On completion of the course, the students will be able to BT Mapping

Course (Highest
Outcome Level)
CO1 Perform and evaluate Matrix Operations K3
CO2 Solve Differential and Integral Equations K3
CO3 Construct Fourier series and Fourier Transforms of the given function K3
CO4 Find the Measures of Central tendency K3
CO5 Analyze Correlation and Regression lines K3
List of Experiments:

1. Find the Inverse, Rank, Eigen values and Eigen Vectors of the matrix.

2. Solve the first order differential equation.

3. Find the integration of ∫ f ( x ) dx .


a

4. Find the Fourier series of f(x).

5. Find the Fourier Transform of f(x).

6. Find the Laplace Transform of f(x).

7. Find the Mean, Median and Mode.

8. Construct the Pie and Bar Diagram.

9. Find the Correlation coefficient.

10. Find the Regression lines.

2
Lecture Periods: - Nil Tutorial Periods: - Nil Practical Periods: 3 0 Total Periods :30
Reference Books
1. T. Veerarajan, “Engineering Mathematics, Tata McGraw Hill Education (India) Private Limited Chennai
2nd Edition Paperback – 1 January 2018.
2. M.K. Venkataraman, “Engineering Mathematics, The National Publishing Company, Madras, 2016.
3. Dr. A. Singaravelu, “Probability and Statistics”, Meenakshi Agency, Paperback – 1, 2019.
Web References
1. https://www.mccormick.northwestern.edu/documents/students/undergraduate/introduction-to-matlab.pdf
2. https://www.nrigroupindia.com/niist/wp-content/uploads/sites/6/2022/02/lab-manual-it406matlab.pdf
3. https://www.studocu.com/row/document/comsats-university-islamabad/signals-and-systems/lab-lab-
manual/38332410

* TE – Theory Exam, LE – Lab Exam

COs/POs/PSOs Mapping
Program Specific
Program Outcomes (POs)
COs Outcomes (PSOs)
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PSO1 PSO2 PSO3
1 2 1 1 1 - 1 - - - - 1 1 1 1
2 3 2 1 1 - 1 - - - - 1 1 1 1
3 2 1 - - - 1 - - - - 1 1 1 1
4 2 1 - - - 1 - - - - 1 1 1 1
5 3 2 1 1 - 1 - - - - 1 1 1 1
Correlation Level: 1 - Low, 2 - Medium, 3 – High

Evaluation Method

Continuous Assessment Marks (CAM)


Performance in practical End Semester
classes Model Total
Assessment Examination
Practical Attendance Marks
Conduction Record (ESE) Marks
viva Examination
of practical work
Marks 15 5 5 15 10 50 100

3
LIST OF EXPERIMENTS

1. Find the Inverse, Rank, Eigen values and Eigen Vectors of the matrix.

2. Solve the first order differential equation.

3. Find the integration of ∫ f ( x ) dx .


a

4. Find the Fourier series of f(x).

5. Find the Fourier Transform of f(x).

6. Find the Laplace Transform of f(x).

7. Find the Mean, Median and Mode.

8. Construct the Pie and Bar Diagram.

9. Find the Correlation coefficient.

10. Find the Regression lines.

4
EX.NO:1
FIND THE RANK, INVERSE, DETERMINANT, EIGEN VALUES AND EIGEN
DATE: VECTORS OF A MATRIX

Aim:
Write a MATLAB program to find the Rank, Inverse, Determinant, Eigen values and Eigen Vectors

of a matrix.

Software Required: MATLAB


Version: R2025a

Algorithm:

Step 1: Start

Step 2: Prompt the user to enter the matrix A.

Step 3: Using rank function(r), rank of matrix is calculated and displays the result.

Step 4: Using det () function, determinant of the matrix of A is calculated and displays the result.

Step 5: Inverse of the matrix A is calculated using inv () function and displays the result.

Step 6: Transpose of the matrix A is calculated using transpose () function and displays the result.

Step 7: Eigenvalues and Eigenvectors of the matrix A calculated using the eig() function. It displays

the eigenvalues (the diagonal of the eigen_values matrix) and the eigenvectors (the columns

of the eigen_vectors matrix).

Step 8: Stop

5
Program:

% Example Matrix
A = input('Enter the Matrix A');

% Rank of the Matrix


R = rank(A);
disp('Rank of A:');
disp(R);

%Determinant of the Matrix


det_A = det(A);
disp('Determinant of A:');
disp(det_A);

% Inverse of the Matrix


i = inv(A);
disp('Inverse of A:');
disp(i);

% Transpose of the Matrix


t = transpose(A);
disp('Transpose of A:');
disp(t);

% Eigen values and Eigen vector of the matrix


[eigen_vectors, eigen_values] = eig(A);
disp('Eigen values of A:');
disp(diag(eigen_values));
disp('Eigen vectors of A:');
disp(eigen_vectors);

Input: Input: Input:

[ 45 36 ] [ ] [ ]
2 2 0 8 −6 2
(i)
(ii) 2 5 0 −6 7 −4
0 0 3
(iii) 2 −4 3
Enter the Matrix A Enter the Matrix A Enter the Matrix A
[4 5; 3 6] [2 2 0;2 5 0;0 0 3] [8,-6,2;-6,7,-4;2,-4,3]
Output: Output: Output:
Rank of A: Rank of A: Rank of A:
2 3 2
Determinant of A: Determinant of A: Determinant of A:
9.0000 18 0
Inverse of A: Inverse of A: Warning: Matrix is singular
to working precision.
0.6667 -0.3333 0.8333 -0.3333 0
6
-0.5556 0.4444 -0.3333 0.3333 0 Inverse of A:
Transpose of A: 0 0 0.3333 Inf Inf Inf
4 5 Transpose of A: Inf Inf Inf
Inf Inf Inf
3 6 2 2 0
Transpose of A:
Eigen values of A: 2 5 0 8 -6 2
1 0 0 3 -6 7 -4
9 Eigen values of A: 2 -4 3
Eigen vectors of A: 1 Eigen values of A:
-0.7071 -0.5145 3 0.0000
0.7071 -0.8575 6 3.0000
15.0000
Eigen vectors of A:
Eigen vectors of A:
-0.8944 0 0.4472 0.3333 0.6667 -0.6667
0.4472 0 0.8944 0.6667 0.3333 0.6667
0 1.0000 0 0.6667 -0.6667 -0.3333

Input:

(iv)
Enter the Matrix A[2,3,-1,-1;1,-1,-2,-4;3,1,3,-2;6,3,0,-7]

Output:
Rank of A:
3
Determinant of A:
-1.4655e-14
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 7.320152e-18.
Inverse of A:
1.0e+15 *

-3.7530 -3.7530 -3.7530 3.7530


2.2518 2.2518 2.2518 -2.2518
1.5012 1.5012 1.5012 -1.5012
-2.2518 -2.2518 -2.2518 2.2518
Transpose of A:
2 1 3 6
3 -1 1 3
-1 -2 3 0
-1 -4 -2 -7

Eigen values of A:

-5.4169 + 0.0000i
1.2084 + 2.1521i
1.2084 - 2.1521i
-0.0000 + 0.0000i

Eigen vectors of A:

7
0.1778 + 0.0000i -0.6870 + 0.0000i -0.6870 + 0.0000i 0.7293 + 0.0000i
-0.7085 + 0.0000i 0.0675 - 0.3752i 0.0675 + 0.3752i -0.4376 + 0.0000i
-0.1381 + 0.0000i 0.1391 + 0.3640i 0.1391 - 0.3640i -0.2917 + 0.0000i
-0.6688 + 0.0000i -0.4804 - 0.0112i -0.4804 + 0.0112i 0.4376 + 0.0000i

PARTICULARS MARKS ALLOTTED MARKS


OBTAINED
Aim & Algorithm 5

Program 10

Output 5

Viva Voce 5

Total 25

Result:
Hence, the program to find the Rank, Inverse, Determinant, Eigen values and Eigen Vectors of a
matrix has been completed successfully.

Applications

Matrix Applications in Network Flow Control (Traffic Systems)

Traffic networks (urban roads, internet packet routes, etc.) can be modelled as directed graphs, where:
 Nodes = intersections or routers
 Edges = roads or links (with capacities, delays, or flow rates)
We use matrices to:
 Model traffic flow
 Analyze congestion
 Optimize routes and control signals

8
Matrix Representation of a Traffic Network
1. Case Study: 4-way Road Network

There are 4 intersections (nodes): A, B, C, and D Vehicles travel one-way only, with the following flows:
 From A to B: 30 cars/hr
 From A to C: 20 cars/hr
 From A to D: 10 cars/hr
 From B to C: 25 cars/hr
 From B to D: 15 cars/hr
 From C to D: 30 cars/hr
Step 1: Define the Flow Matrix F
The flow matrix F (4×4), where F ij is the number of vehicles flowing from node i to node j:

[ ]
0 30 20 10
0 0 25 15
F=
0 0 0 30
0 0 0 0

Each row represents outgoing flows, and each column represents incoming flows.
This upper triangular matrix shows traffic only moving forward (one-way flow).

Step 2. Rank of the Flow Matrix


 To check the independent flow paths.
 The rank of matrix F tells us how many independent traffic routes exist.
 If rank < number of nodes, then some routes are dependent or redundant.
 Helps in identifying bottlenecks or overlapping paths.
 A full rank matrix (rank = 3 or 4) means maximum independent routes.

We can compute the rank using MATLAB


rank(F)

Here the matrix has rank 3, meaning:

 This means 3 independent traffic routes exist among the 4 intersections.


 So, 1 route is redundant — indicating possible rerouting flexibility.
 One route (e.g., C→D) may be linearly dependent (a combination of A→C and B→C→D)
📌 Interpretation: There's redundancy — we can potentially reroute traffic without loss of flow.

Step 3: Use Inverse of a Delay Matrix to Optimize Traffic Signals


 Let’s now say we define a delay matrix D , which models travel delay in minutes:

[ ]
0 5 7 10
0 0 4 6
D=
0 0 0 3
0 0 0 0

We now want to control traffic lights to minimize total delay.


Let x be a vector of signal green time adjustments for each road, and t be the target delay vector for
9
each route (say [15; 12; 9; 0] minutes).
Solve:
−1
Dx=t ⇒ x=D t
Use inverse (or pseudo-inverse) to find optimal timings. Example in MATLAB:
x = pinv(D) * t;

📌 Interpretation: We find adjustments to traffic signals to meet desired flow times.

Step 4: Analyze Network Flow Stability Using Eigenvalues


We define a transition matrix T based on how vehicles move between nodes (normalized version of flow
matrix):

[ ]
0 0.4 0.3 0.3
0 0 0.6 0.4
T=
0 0 0 1.0
0 0 0 0

Each entry shows the probability of moving from one node to another.
Compute Eigenvalues:
Use: MATLAB Code eig(T)
The eigenvalues are:
λ=[0 , 0 , 0 , 0]
📌 Interpretation:
 All eigenvalues are zero → traffic fully exits the network without cycling back.
 This confirms a stable network with no buildup or cyclic congestion.
🔍 Eigenvalue Analysis:
 Positive eigenvalue → traffic builds up (congestion)
 Negative eigenvalue → traffic dissipates (stable)
 Eigenvectors → show flow direction patterns (dominant congested routes)
📌 Used in:
 Predicting future congestion spots
 Designing robust routing algorithms in data or vehicle networks

MATLAB Code
% Define Nodes
nodes = {'A', 'B', 'C', 'D'};

% Define Edges (From -> To)


sources = {'A', 'A', 'A', 'B', 'B', 'C'};
targets = {'B', 'C', 'D', 'C', 'D', 'D'};
flows = [30, 20, 10, 25, 15, 30]; % cars per hour

% Create Directed Graph


G = digraph(sources, targets, flows, nodes);
10
% Plot the Graph
figure;
h = plot(G, 'Layout', 'layered', 'EdgeLabel', G.Edges.Weight, ...
'LineWidth', 2, 'ArrowSize', 12, 'NodeColor', 'skyblue', ...
'NodeFontSize', 12, 'EdgeFontSize', 11);
title('Traffic Flow Between Intersections (cars/hour)');

% Optional: Display Adjacency Matrix


adjMatrix = full(adjacency(G, 'weighted'));
disp('Weighted Adjacency Matrix (cars/hour):');
disp(array2table(adjMatrix, 'VariableNames', nodes, 'RowNames', nodes));

Output:

Inference:
The rank, inverse, determinant, eigenvalues, and eigenvectors of a matrix are crucial in IT for
understanding data structure and system behavior—rank tells us about redundancy and data dimensions;
the inverse is key for solving linear systems and cryptography; the determinant helps check solvability and
stability; and eigenvalues/eigenvectors enable powerful techniques like principal component analysis, web
ranking, and efficient image and signal processing, making these concepts foundational for machine
learning, network analysis, graphics, and modern computation.

EX.NO:2
DRAW THE GRAPH OF FIRST ORDER DIFFERENTIAL EQUATION
DATE:

Draw the graph of first order differential equation

Aim:

Write a program to plot the graph of first order differential equation.

11
Software Required: MATLAB

Version: R2025a

Algorithm:

Step 1: Start

Step 2: Prompt the user to enter the ordinary differential equation represent as f(x)

eg:(f = @(x,y)-2*y;).

Step 3: Set initial condition for the ordinary differential equation equal to 1

eg:(y(0) = 1).

Step 4: xvalues = linspace(Assume the range for x and y values ); This generates 100 evenly

spaced points between 0 and 5, which will be used as the independent variable values

for which the corresponding y values will be computed.

Step 5: The results are stored in x variable and y variables and using the solver function is

called to numerically solve the ODE defined by F over the range specified in x values,

starting from the initial condition.

Step 6: The plot function creates a blue line ('b-') with a line width of 1.5. The axe are

labeled, a title is added.

Step 7: A grid is enabled for better visualization.

Step 8: Stop

Program:
% y is the dependent variable, x is the independent variables
% dy/dx = - 2y
F = @(x,y)-2*y;
% define the initial condition y(0) = 1
initialcondition=1;
% define the x values for which you want to obtain the corresponding y
% values
xvalues = linspace(0,5,100); % change the range and no of points as needed
% solve the F using F45
[xSol,ySol]=ode45(F,xvalues,initialcondition);
% plot the solution
plot(xSol,ySol,'b-','LineWidth',1.5);

12
xlabel('x');
ylabel('y(x)');
title('Solution of the First order ODE: dy/dx = -2*y');
grid on;
Output:
(i) Initial condition y (0) = 1 (ii) Initial condition y (0) = 2

(i) Initial condition y (0) = 1 (ii) Initial condition y (0) = 2

13
PARTICULARS MARKS ALLOTTED MARKS OBTAINED

Aim & Algorithm 5

Program 10

Output 5

Viva Voce 5

Total 25

Result:
Hence, the program to draw the graph of first order differential equation has been completed
successfully.

14
Application for First-Order Differential Equation in Traffic Flow

Single-Lane Road with Incoming and Outgoing Flow


Imagine a stretch of road (like a toll gate or narrow bridge) where:
 Cars enter at a constant rate Rin
 Cars exit proportionally to the number of cars already present — i.e., the longer the queue, the
faster cars exit
Let:
 y (t ) = number of vehicles on the road segment at time t
 Rin = constant inflow rate (e.g., 20 cars per minute)
 k = proportionality constant for outflow rate (e.g., 0.1 per min)

Step 1: Form the Differential Equation


dy
=Rin −k ⋅ y (t)
dt
This is a first-order linear differential equation — it models:
 Inflow adds vehicles constantly.
 Outflow increases with the number of vehicles already in the system (more congestion = faster
exit).

Step 2: Solve the Equation


This ODE has the general solution:
Using MATLAB code
initialcondition=1;
xvalues = linspace(0,5,100); [xSol,ySol]=ode45(F,xvalues,initialcondition);

y (t )=
R in
k ( R
)
+ y 0− in e−kt
k

Where:
 y 0 is the initial number of vehicles at t=0

Example: Plug in Real Numbers


 Rin =20 cars/min
 k =0.1
 y 0=0 (empty initially)

20
y (t )= ( 1−e−0.1 t )=200 (1−e−0.1 t )
0.1

15
Here’s the graph of the first-order differential equation model for traffic queue buildup:
It shows:
 The blue curve shows how the number of cars increases over time.
 The red dashed line at 200 cars is the steady state — where inflow equals outflow.
 Initially, the number of cars rises rapidly, then levels off as it approaches the steady state.

Interpretation:
 As t → ∞ , y (t )→ 200: this is the steady state (inflow = outflow)
 For small t , y (t ) increases exponentially
 This models how a road fills up and stabilizes over time

Inference:
First-order differential equations in the IT field are fundamental for modeling the rate of change in
processes such as signal filtering, population dynamics in simulations, real-time network traffic, and
feedback mechanisms in machine learning algorithms; they provide essential tools for predicting system
behavior, optimizing response times, and automating control processes in computational and engineering
applications.

16
EX.NO:3
b
DATE: FIND THE INTEGRATION OF ∫ f ( x ) dx
a

Find the integration of given function

Aim:
b

Write a program to find the integration of ∫ f ( x ) dx .


a

Software Required: MATLAB

Version: R2025a

Algorithm:

Step 1: Start

Step 2: Prompt the user to enter the function (Ex: f=@(x) sin(x);).

Step 3: Set the lower limit(a) and upper limit(b) of integration. Set a as 0 and b as pi.

Step 4: Using integral function, computes the definite integral of the function f from a to

b.

Step 5: Print the result of the integral to show the limits and computed integral

value.

Step 6: Stop

17
Program:

% Define the function


f = @(x) sin(x);

% Generate x values from 0 to pi


x = linspace(0, pi, 100); % Adjust the number of points (100 here) for smoother or coarser plot

% Evaluate the function at these x values


y = f(x);

% Plot the function


plot(x, y, 'b-', 'LineWidth', 2);
grid on;
title('Plot of f(x) = sin(x)');

xlabel('x');
ylabel('f(x)');
xlim([0, pi]);

% Optionally, add grid and labels


grid on;

Output:

(i)The integral of sin(x) from 0 to pi is: 2.0000 (ii)The integral of cos(x) from 0 to pi/2 is: 1.0000

(iii)The integral of cos(x) from 0 to pi is: 1.0000 (iv)The integral of tan (x) from 0 to pi

18
PARTICULARS MARKS ALLOTTED MARKS OBTAINED
Aim & Algorithm 5
Program 10
Output 5
Viva Voce 5
Total 25

Result:
b

Hence, the program to find the integration of ∫ f ( x ) dx has been completed successfully.
a

19
Applications of Integration in Traffic Density Analysis
Traffic Density on a Road Segment
Imagine a 5-km stretch of highway where:
 The density of cars (cars per kilometer) is not uniform.
 The density is given by a function:

ρ(x )=50+10 sin ( πx5 )


where x is the distance from the start (in km), and ρ(x ) is cars/km.

Find the total number of vehicles on the entire 5 km stretch.


Step 1: Set Up the Definite Integral

( ( πx5 )) dx
5 5
Total Cars=∫ ρ(x )dx=∫ 50+ 10 sin
0 0

This is a definite integral over the interval [0 ,5 ] km.

Step 2: Solve the Integral


Evaluate:

( ( πx5 )) dx
5

∫ 50+10 sin
0

This gives the total number of vehicles over the road segment.
Using MATLAB code
Define the density function: ρ(x) = 50 + 10 * sin(pi * x / 5)
rho = @(x) 50 + 10 * sin(pi * x / 5);
% Compute the definite integral from x = 0 to x = 5
total_cars = integral(rho, 0, 5);
% Display the result
fprintf('Total number of cars over the 5 km road: %.2f\n', total_cars);
% Plotting the density function
x = linspace(0, 5, 300);
y = rho(x);

figure;
plot(x, y, 'b-', 'LineWidth', 2);
hold on;

area(x, y, 'FaceColor', [0.5 0.8 1], 'EdgeColor', 'none', 'FaceAlpha', 0.3);


title(['Traffic Density over a 5 km Road Segment. Total Cars ≈ ', num2str(total_cars, '%.2f')]);
xlabel('Distance x (km)');
ylabel('Density ρ(x) (cars/km)');
grid on;
legend('\rho(x)', 'Total Cars (area under curve)', 'Location', 'NorthEast');

20
The graphical output is

Final Result:
The total number of vehicles on the 5 km road segment is approximately:
281.83 cars
This Shows:

 The density function ρ(x )=50+10 sin ( πx5 ) models variable traffic (denser near middle of the
road).
 The definite integral computes the total number of cars by summing density over the length.
 The shaded area under the curve in the graph represents this total — a practical use of definite
integration in traffic flow.

Real-World Applications:
 Traffic load estimation on roads/highways
 Smart city planning (deciding where to widen roads or add lanes)
Data transfer load in computer networks (where “density” = data packets/km)

Inference:
Integration in the IT field is essential for tasks such as calculating areas under curves for data
analytics, finding cumulative totals in databases, solving continuous models in machine learning,
designing digital filters in signal processing, and modeling real-world phenomena using differential
equations—making it a fundamental technique for analysis, optimization, and engineering solutions across
computing and technology applications.

21
EX.NO:4
DRAW THE GRAPH OF THE FUNCTION f (x) AND ITS FOURIER
DATE: SERIES

Draw the graph of the function f(x) and its Fourier series

Aim:
Write a program to draw the graph of the function f(x) and to find its Fourier series of f(x).

Software Required: MATLAB


Version: R2025a

Algorithm:
Step 1: Initialization
Clear all variables and the command window using clear; clc;
Define the half-period L=π
Set the number of Fourier terms N=10
Step 2: Define the Function
Define the full wave rectified sine function: f (x)=¿ sin(x)∨¿
Step 3: Initialize Fourier Coefficients
Initialize a0 for the average value
Initialize arrays an and bn to store Fourier cosine and sine coefficients
Step 4: Compute Fourier Coefficients
L
1
Compute a 0: a 0= ∫ f ( x)dx
2 L −L

Loop over n=1 to N to compute:

o Cosine coefficients a n:

L
1
a n= ∫ f (x)cos
L −L L( )
nπx
dx

o Sine coefficients b n:

L
1
b n= ∫ f (x)sin
L −L L( )
nπx
dx

22
Step 5: Construct Fourier Series
Start with the DC component: FourierSeries ( x)=a0

Iteratively add each term:

[ ( ) ( )]
N
nπx nπx
Fourier series(x )=a0 + ∑ an cos +bn sin
n=1 L L

Step 6: Plotting
Define x values from −π to π
Plot the original function f (x)=¿ sin(x)∨¿

Program:

% Fourier Series of a Square Wave Function


clear; clc;

% Define the period of the square wave


L = pi;

% Number of Fourier terms to calculate


N = 10;

% Define the square wave function


F = @(x) sign(sin(x)); % Square wave function

% Initialize Fourier coefficients


a0 = 0;
an = zeros(1, N);
bn = zeros(1, N);

% Calculate a0 (the average value)


a0 = (1 / (2 * L)) * integral(@(x) F(x), -L, L);

% Calculate an and bn coefficients


for n = 1:N
an(n) = (1 / L) * integral(@(x) F(x) .* cos(n * pi * x / L), -L, L);
bn(n) = (1 / L) * integral(@(x) F(x) .* sin(n * pi * x / L), -L, L);
end

% Define the reconstructed function using Fourier series


FourierSeries = @(x) a0;
for n = 1:N
FourierSeries = @(x) FourierSeries(x) + an(n) * cos(n * pi * x / L) + bn(n) * sin(n * pi * x / L);

23
end

% Plot the original function and the Fourier series approximation


x = linspace(-L, L, 1000);
figure;
plot(x, F(x), 'r', 'LineWidth', 1.5); % Original function
hold on;
plot(x, FourierSeries(x), 'b--', 'LineWidth', 1.5); % Fourier series approximation
legend('Original Function', 'Fourier Series Approximation');
title('Fourier Series Approximation of a Square Wave');
xlabel('x');
ylabel('F(x)');
grid on;

Output:

(i) (ii)

(iii) (iv)

24
PARTICULARS MARKS ALLOTTED MARKS
OBTAINED

Aim & Algorithm 5

Program 10

Output 5

Viva Voce 5

Total 25

Result:
Hence, the program to draw the graph of the function f(x) and to find its fourier series of f(x) has
been completed successfully.

25
Applications of Fourier Series in Signal Compression / Traffic Load Pattern

Traffic Load Repeats Daily (Periodic Signal)


Imagine a traffic sensor on a highway records vehicle flow (cars per hour) that repeats every 24 hours.
A simplified periodic pattern:
 High during 8 – 10 AM and 5 – 7 PM
 Low during night
 Repeats every 24 hours
We approximate this traffic load using a Fourier series, which breaks the pattern into:
 A DC component (a₀) = average traffic
 Sine and cosine components (harmonics) = peak fluctuations

Step-by-Step Problem
Let the function:

{
100 , 0<t <6
200 , 6<t <10
f (t)= 120 , 10<t <16
250 , 16<t <20
80 , 20<t< 24

Let’s assume it repeats every T =24 hours.


Now compute the Fourier series approximation of this function using MATLAB.
MATLAB Code: Fourier Series Approximation
clc; clear;

% Period
L = 12; % Since the full period is 24, use L = T/2 for standard Fourier form
T = 2 * L;

% Define the piecewise traffic function over one period


f = @(t) (t < 6).*100 + ...
((t >= 6) & (t < 10)).*200 + ...
((t >= 10) & (t < 16)).*120 + ...
((t >= 16) & (t < 20)).*250 + ...
(t >= 20).*80;

% Number of Fourier terms to compute


N = 10;

% Compute a0 (average traffic)


a0 = (1/T) * integral(f, 0, T);

% Initialize arrays
an = zeros(1, N);
bn = zeros(1, N);

26
% Compute Fourier coefficients
for n = 1:N
an(n) = (1/L) * integral(@(t) f(t) .* cos(n * pi * t / L), 0, T);
bn(n) = (1/L) * integral(@(t) f(t) .* sin(n * pi * t / L), 0, T);
end

% Reconstruct the signal using Fourier Series


t_vals = linspace(0, T, 1000);
f_approx = a0 / 2 * ones(size(t_vals));

for n = 1:N
f_approx = f_approx + an(n) * cos(n * pi * t_vals / L) + bn(n) * sin(n * pi * t_vals / L);
end

% Plot original and Fourier approximation


figure;
plot(t_vals, f(t_vals), 'r', 'LineWidth', 1.5); hold on;
plot(t_vals, f_approx, 'b--', 'LineWidth', 1.5);
legend('Original Traffic Flow', 'Fourier Series Approximation');
xlabel('Time (hours)');
ylabel('Traffic Load (cars/hour)');
title('Fourier Series Approximation of Periodic Traffic Load');
grid on;
The graphical output is

Here
 Red line: Original traffic pattern (step-like)
 Blue dashed line: Smooth Fourier approximation using 10 terms
As N increases, the approximation becomes more accurate

 Average Traffic Flow (a₀):

a 0=143.33 cars/hour
This represents the mean flow over 24 hours.

27
First 3 Fourier Coefficients:

Term Value
a1 −30.13
a2 −52.38
a3 +19.10
b1 −19.33
b2 −15.92
b3 +33.95

These sine and cosine terms encode the variation (peaks and dips) in traffic throughout the day.

Interpretation:
Term Meaning
a0 Average traffic flow (baseline signal)
an, bn Capture periodic fluctuations (morning/evening peaks)
Reconstructed f (t) Approximated real-world traffic pattern

Inference:
Fourier series are widely used in the IT field for decomposing complex periodic signals into
sums of sine and cosine waves, enabling efficient signal analysis, compression, noise reduction in audio
and image processing, solving differential equations, and powering technologies in telecommunications,
computer graphics, and data science by transforming data between time and frequency domains for
powerful analytical and computational applications.

28
EX.NO:5
DATE: FIND THE FOURIER TRANSFORM OF f(x)

Find the Fourier Transform of f(x)

Aim:

Write a program to find the Fourier Transform of f(x).

Software Required: MATLAB

Version: R2025a

Algorithm:

Step 1: Start

Step 2: Declares x and xi as symbolic variables.

Step 3: exp() defines a symbolic function (f(x))

Step 4: The Fourier transform that transforms a function of time (or space) into a function of

frequency and frequency() into the frequency components of the original function.

Step 5: Print the results, first display the output of a string indicating and

second display outputs the computed Fourier transform of the function

Step 6: Stop

29
Program:

% Define the function f(x) = exp(-x^2)


f = @(x) exp(-x.^2);

% Parameters
L = 10; % Length of the interval [-L, L]
N = 2^10; % Number of points for numerical integration and FFT
% Define the x values and the function f(x)
x = linspace(-L, L, N);
y = f(x);

% Compute the Fourier transform using numerical integration


dk = 2*pi / (2*L); % Frequency step size
k = (-N/2:N/2-1) * dk; % Frequency values

F = fftshift(fft(y)) * (2*L/N); % Perform FFT and adjust scaling

% Plotting
figure;
subplot(2, 1, 1);
plot(x, y, 'b-', 'LineWidth', 2);
title('f(x) = e^{-x^2}');
xlabel('x');
ylabel('f(x)');
grid on;

subplot(2, 1, 2);
plot(k, abs(F), 'r-', 'LineWidth', 2);
title('Fourier Transform of f(x)');
xlabel('k');
ylabel('|F(k)|');
grid on;

30
% Adjust the x-axis limits to focus on central frequencies
xlim([-10, 10]);

% Adjust plot layout


sgtitle('Fourier Transform of f(x) = e^{-x^2}');

Output:

31
PARTICULARS MARKS ALLOTTED MARKS OBTAINED
Aim & Algorithm 5
Program 10
Output 5
Viva Voce 5
Total 25

Result:
Hence, the program to find the Fourier Transform of f(x) has been completed successfully.

32
Applications of Fourier Transform Works in Image Processing

Step 1: Load the Image


 An image is a 2D matrix of pixel values.
 For grayscale images: f (x , y )∈[0 , 255]
📌 Code: img = imread('image.png');
It seems a pattern with unwanted lines or blur.

Step 2: Apply 2D Fourier Transform (FFT)


 Use 2D Fast Fourier Transform (FFT2):
M −1 N−1 −j2π ( uxM + vyN )
F (u , v )= ∑ ∑ f (x , y )⋅ e
x=0 y=0
 This converts spatial image into its frequency components.

📌 Code: F = fft2(double(img_gray));

Step 3: Shift the Spectrum to Center


 The zero-frequency (DC component) is at the corner by default.
 Use fftshift to move low frequencies to the center.
📌 Code: F_shift = fftshift(F);

Step 4: Visualize the Frequency Spectrum


 Compute the magnitude of complex frequency values:
Magnitude=log ¿
 Bright points away from center indicate noise or fine patterns.
📌 Code: imshow(log(1 + abs(F_shift)), []);

Step 5: Apply a Filter (Modify Frequency Domain)


 Example: Remove high-frequency noise using a Low-Pass Filter:
o Create a mask that only keeps frequencies near center
o Multiply mask with frequency spectrum:
F filtered (u , v )=F (u , v )⋅Mask (u , v )

📌 Code:
mask = sqrt((X - centerX).^2 + (Y - centerY).^2) < radius;
F_filtered = F_shift .* mask;
Step 6: Inverse Fourier Transform
 Use inverse FFT (ifft2) to convert back to the image:

f (x , y )=Re [ifft2(ifftshift(F filtered ))]


📌 Code: filtered_image = real(ifft2(ifftshift(F_filtered)));
Step 7: Display the Cleaned Image
 Show the new image which is now denoised, sharpened, or compressed, depending on the filter
used.

33
📌 Code: imshow(uint8(filtered_image));

MATLAB CODE:
%REMOVAL OF PERIODIC NOISE FROM IMAGE.

function RemovePeriodicNoise(img)
% take FT of image and
% shift corners to center.
Fourier_transform=fft2(img);
Centered_shifted=fftshift(Fourier_transform);

% Block the noise spectrum.


Centered_shifted(1:125,110:130)=0;%for man
Centered_shifted(190:320,110:130)=0;%diagonals

Centered_shifted(120:x,1:100)=0;%for lady with hat.


Centered_shifted(1:100,120:y)=0;%diagonals.

% inverse shift center to


% corner and take Inverse FT.
Inverse_shifted=ifftshift(Centered_shifted);
Output_image=ifft2(Inverse_shifted);

% display input image.


original_input_image=img;
imtool(original_input_image,[]);

% display FT spectrum.
Centered_shifted_spectrum=abs(log(fftshift(Fourier_transform)));
imtool(Centered_shifted_spectrum,[]);

% display denoised FT.


Noise_free_FT=log(Centered_shifted);
imtool(Noise_free_FT,[]);

% display output image.


imtool(abs(Output_image),[]);
end

%%%UTILITY CODE%%%
k=imread("periodic_noise1.png");
RemovePeriodicNoise(k);

Output:

34
Inference:
The Fourier transform is a mathematical technique essential in IT for converting signals from the
time domain to the frequency domain, which is crucial for signal processing, image analysis, data
compression, and filtering. It allows complex signals to be represented as sums of simple sinusoids,
enabling efficient manipulation and understanding of frequency components in applications such as
telecommunications, audio processing, medical imaging, and machine learning.

35
EX.NO:6
DATE: FIND THE LAPLACE TRANSFORMATION OF f(x)

Compute the Laplace transform of 1/sqrt(x). By default, the transform is in terms of s.

Aim:

Write a MATLAB program to Compute the Laplace transform of 1/sqrt(x). By

default, the transform is in terms of s.

Software Required: MATLAB

Version: R2025a

Algorithm:

Step 1: Start

Step 2: Declares x and xi as symbolic variables, allowing them to be used in symbolic

expressions.

Step 3: f = 1/sqrt(x) = 1/√x.

Step 4: The Laplace transform function converts a function of a real variable x (often time) to a

function of a complex variable (frequency).

Step 5: The result F will be the Laplace transform of 1/√x, which is √(π/s).

Step 6: Stop

36
Program:
% Define the function f(x) = 1/sqrt(x)
f = @(x) 1 ./ sqrt(x);

% Define the range for the Laplace variable s


s = linspace(0.1, 10, 100);

% Allocate space for the Laplace transform values


F_s = zeros(size(s));

% Numerical integration using MATLAB's integral function


for i = 1:length(s)
F_s(i) = integral(@(x) exp(-s(i)*x) .* f(x), 0, Inf);
end

% Plotting the Laplace transform


figure;
plot(s, F_s, 'b-', 'LineWidth', 2);
title('Laplace Transform of f(x) = 1/\surd(x)');
xlabel('s');
ylabel('F(s)');
grid on;

Output:

(i) f(x) = 1/sqrt(x) (ii) f(x) = 1/sqrt(4x)

37
PARTICULARS MARKS ALLOTTED MARKS OBTAINED
Aim & Algorithm 5
Program 10
Output 5
Viva Voce 5
Total 25

Result:
Hence, the program to Compute the Laplace transform of 1/sqrt(x). By default, the transform is in
terms of s has been completed successfully.

38
Applications
Modeling a Queue in a Network Server using Laplace Transform
A web server receives requests from users. Each request waits in a queue if the server is busy. To analyze
the response time of the system when a burst of traffic comes in.
Model this using a First Order Linear ODE, which is common in:
 Queuing theory
 Network latency modeling
 Control system design in embedded software

Theoretical Model:
Step 1: Understand the Physical System
 A server handles incoming traffic (e.g., HTTP requests).
 At t=0 , a unit step input begins: traffic starts flowing steadily.
 The system takes time to process, leading to a buildup (queue) that eventually levels off.
Let:
 y (t ): queue length (number of pending requests)
 u(t ): input function (unit step: traffic starts)
 τ : time constant (server response time)
This is a first-order linear differential equation.
Step 1: Given ODE
i.e queue size can be define as
dy 1
+ y (t )=u(t ), y (0)=0
dt τ
Let τ =2 seconds (moderate delay)
Step 2: Apply Laplace Transform
Take Laplace transform of both sides:
1 1
sY (s)− y ( 0)+ Y (s)=
τ s
Since y (0)=0, we get:

( 1τ )= 1s
Y (s) s+

Step 3: Solve for Y (s)

Substitute τ =2:

( 12 )= 1s ⇒ Y (s)= s s+1 1
Y (s) s+
( 2)

39
Step 4: Use Partial Fraction Decomposition
1 A B
= +
( 12 )
s s+
s
s+
1
2

Solve:
1
 A(s+ )+ Bs=1
2
 A=2 , B=−2
So,
2 2
Y (s)= −
s 1
s+
2

Step 5: Take Inverse Laplace


Using Laplace pairs:
 L
−1 1
s {}
=1

 L
−1 1
{ }
s +a
=e−at
−t / 2
y (t )=2−2 e
Final Answer:

y (t )=2 ( 1−e−t / 2 )

Interpret the Result


 At t=0 : y (0)=0 → no queue yet

 As t → ∞ : y (t )→ 2 → queue stabilizes

 The curve rises exponentially toward 2

MATLAB Code – Laplace Transform in Server Queue Model


clc; clear; close all;

% Define time vector


t = linspace(0, 10, 1000); % Simulate for 0 to 10 seconds

% System response: y(t) = 2 * (1 - exp(-t/2))


tau = 2; % Time constant (delay factor)
y = 2 * (1 - exp(-t / tau));

% Plot the solution


plot(t, y, 'b-', 'LineWidth', 2);
grid on;
title('Response of Network Server Queue to Sudden Burst Traffic');
xlabel('Time (seconds)');
ylabel('Pending Requests y(t)');

40
legend('y(t) = 2(1 - e^{-t/2})');
ylim([0 2.2]);

Output:

Here
 The blue curve starts at 0 (no pending requests)
 Rises sharply as traffic hits the server
 Gradually stabilizes at y = 2, which is the maximum number of pending requests (due to unit input
and τ = 2)

Inference:
The Laplace transform is a powerful mathematical tool widely used in the IT field to convert time-
domain functions into the complex frequency domain, simplifying the solution of differential equations
and system analysis. Its applications include analyzing and designing control systems, electrical circuit
behavior, signal processing, and solving initial-value problems, making complex dynamic and transient
behaviors easier to understand and compute efficiently.

41
EX.NO:7
FIND THE MEAN, MEDIAN AND MODE.
DATE:

Find the Mean, Median and Mode.

Aim
Write a MATLAB program for the data = [23, 25, 29, 34, 34, 35, 36, 40, 44, 44, 44, 50, 52, 55, 60,
65, 70, 75, 80, 85, 85, 85, 90]; to find the Mean, Median and Mode.

Software Required: MATLAB


Version: R2025a

Algorithm:

Step 1: Start

Step 2: Initializes an array called data containing a series of numerical values.

Step 3: Computes the average of the numbers in data and stores it in mean_value.

Step 4: Finds the middle value of the sorted data and stores it in median_value.

Step 5: Determines the most frequently occurring number in data and stores it
in mode_value.
Step 6: Print the calculated mean, median, and mode to the command window,
formatted to two decimal places.
Step 7: Stop

42
Program:
% Given data

data = [23, 25, 29, 34, 34, 35, 36, 40, 44, 44, 44, 50, 52, 55, 60, 65, 70, 75, 80, 85, 85, 85, 90];

% Calculate mean, median, and mode

mean_value = mean(data);

median_value = median(data);

mode_value = mode(data);

% Display the results

disp(['Mean: ', num2str(mean_value)]);

disp(['Median: ', num2str(median_value)]);

disp(['Mode: ', num2str(mode_value)]);

% Plot the data

figure;

hold on;

% Plot the data points

plot(data, 'bo-', 'DisplayName', 'Data');


% Plot mean
yline(mean_value, 'r--', 'LineWidth', 2, 'DisplayName', ['Mean: ', num2str(mean_value)]);
% Plot median
yline(median_value, 'g-.', 'LineWidth', 2, 'DisplayName', ['Median: ', num2str(median_value)]);
% Plot mode
yline(mode_value, 'm-', 'LineWidth', 2, 'DisplayName', ['Mode: ', num2str(mode_value)]);
% Enhance plot
title('Mean, Median, and Mode of Data');
xlabel('Index');
ylabel('Value');
legend show;

43
grid on;
hold off;

Output:

(i) data = [23, 25, 29, 34, 34, 35, 36, 40, 44, 44, 44, 50, 52, 55, 60, 65, 70, 75, 80, 85, 85, 85, 90];

(ii) data = [45, 47, 48, 50, 52, 54, 55, 55, 57, 58, 60, 62, 65, 65, 66, 68, 70, 72, 75, 78, 78, 80, 85];

PARTICULARS MARKS ALLOTTED MARKS OBTAINED


Aim & Algorithm 5
Result: Program 10
Hence, the
program Output 5 to find the
Mean, Viva Voce 5 Median
and Mode has been
Total 25
completed
successfully.
Applications

44
Server Load Balancing Using Mean CPU Usage
An IT company runs 3 servers to handle user traffic. Each server reports its CPU usage every minute.
You want to decide when to add a new server or redistribute traffic if the mean CPU usage exceeds a
threshold.
Step-by-Step Working Process
Step 1: Collect CPU Usage Data
Assume CPU usage is sampled for 5 minutes from 3 servers:

Time
(min) Server 1 (%) Server 2 (%) Server 3 (%)
1 40 60 50
2 45 65 52
3 48 70 53
4 50 72 55
5 52 75 60

Step 2: Compute Mean CPU Usage per Server


For each server, compute:
Server 1:
40+45+ 48+50+52
Mean 1= =47
5
Server 2:
60+ 65+70+72+75
Mean 2= =68.4
5
Server 3:
50+52+53+55+ 60
Mean 3 = =54
5
Step 3: Set a Threshold (e.g., 60%)
If average usage > 60%, we consider the server overloaded.

Mean
Server CPU Status
S1 47% OK
S2 68.4% 🚨 Overloaded
S3 54% OK

Step 4: Take Action Based on Mean


 Server 2 is overloaded
 Options:
a. Migrate some tasks from Server 2 → Server 1 or 3
b. Spin up a new server (auto-scaling)
c. Trigger load balancer to shift future requests
45
Step 5: Optional – Use MATLAB to Automate This
cpu_data = [
40, 60, 50;
45, 65, 52;
48, 70, 53;
50, 72, 55;
52, 75, 60
];

mean_cpu = mean(cpu_data); % Mean usage across time per server


disp('Mean CPU usage per server:');
disp(mean_cpu);

% Set threshold
threshold = 60;
overloaded = find(mean_cpu > threshold); % Index of overloaded servers
disp('Overloaded servers:');
disp(overloaded);

Output:

Median in Server Response Time Analysis


The monitor server response times (in ms) for incoming user requests.
You want a measure that's not affected by outliers (e.g., one slow request), so you use the median instead
of the mean.
Step-by-Step Process:
Step 1: Sample Response Times
From a server log, you record response times for 9 requests:
[95, 100, 105, 110, 115, 120, 125, 130, 1000]
Here, 1000 ms is an outlier.
Step 2: Sort the Data
[95 ,100 ,105 , 110 , 115 , 120 , 125 ,130 , 1000]

46
Step 3: Find the Median
 Odd number (9) ⇒ Median = 5th value
Median - 115
🟢 This gives a typical response time unaffected by the outlier 1000.

Mode in Server Error Logs


If anyone log HTTP status codes returned by a server.
[200, 200, 404, 200, 503, 404, 500, 200, 404, 200]
Step-by-Step Process:
Step 1: Tally Frequencies
Status Frequency
Code
200 5
404 3
503 1
500 1
Identify the Mode
 Mode = most frequent value
Mode=200
CODE: MATLAB Snippet (Optional)
response_times = [95, 100, 105, 110, 115, 120, 125, 130, 1000];
error_codes = [200, 200, 404, 200, 503, 404, 500, 200, 404, 200];

median_val = median(response_times);
mode_val = mode(error_codes);

disp(['Median response time: ', num2str(median_val)]);


disp(['Most common error code (Mode): ', num2str(mode_val)]);
Output:
Median response time: 115

Inference:
The mean, median, and mode are basic measures of central tendency in statistics used to
summarize a data set. The mean is the average of all values, calculated by adding them and dividing by the
total count. The median is the middle value when the data is ordered, providing a central point robust to
outliers. The mode is the most frequently occurring value, useful for identifying common or popular data
points. Together, they help describe the typical or representative value in a dataset, with the mean sensitive
to extreme values, the median offering a better measure for skewed data, and the mode highlighting the
most common observations.

47
EX.NO:8
CONSTRUCT THE PIE AND BAR DIAGRAM
DATE:

a) Pie Diagram

Aim:
Write a MATLAB program for the categories =

'Category1','Category2','Category3','Category4','Category5'};

data = [15,30,10,25,20]; to Construct the Pie Diagram

Software Required: MATLAB


Version: R2025a

Algorithm:
Step 1: Start
Step 2: Define the categories and their corresponding data values.
Step 3: Using the pie() function, the first subplot creates a basic pie chart, where the data
values are plotted as slices and the category labels are displayed.
Step 4: The second subplot creates an exploded pie chart by passing an exploded vector to
the pie() function. The first element of the exploded vector is set to 0.1, which
causes the first slice to be slightly separated from the rest of the chart.
Step 5: The third subplot creates a donut chart by using the pie() function and then
modifying the resulting plot.
Step 6: The donut variable stores the output of the pie() function, and the p variable selects
the patch objects representing the slices.
Step 7: The set() function is used to remove the edge color of the slices, creating the donut
effect.
Step 8: Add title and display.
Step 9: Stop.

48
Program:

% Sample Data
categories = {'Category1','Category2','Category3','Category4','Category5'};
data = [15,30,10,25,20];

% Create a basic pie chart


figure;
subplot(1,3,1);
pie(data, categories);
title('Basic Pie Chart');
hold on;

% Create a Exploded Pie Chart


subplot(1,3,2);
exploded=[0.1,0,0,0,0]; % Explode the first slice
pie(data, exploded, categories);
title('Exploded Pie Chart');
hold on;

% Create a donut chart


subplot(1,3,3);
donut = pie(data, categories);
p = donut(1:2:end);
set(p,'EdgeColor','none'); % Remove slice edges to create a donut
title('Donut Chart');
hold on;

% Adjust layout
sgtitle('DIFFERENT TYPES OF PIE CHARTS');

Output:
(i)data = [15,30,10,25,20]

49
PARTICULARS MARKS ALLOTTED MARKS OBTAINED
Aim & Algorithm 5
Program 10
Output 5
Viva Voce 5
Total 25

Result:
Hence, the program to Construct the Pie Diagram has been completed successfully.

Inference:
A pie chart is a circular graph that represents data as slices of a whole, making it easy to
visualize proportions within a dataset. Each slice corresponds to a category’s percentage of the total,
with the entire circle representing 100%. Pie charts are especially helpful for showing how parts
contribute to the whole in an intuitive and visually appealing way, commonly used in business,
marketing, and education to present sales data, survey results, and budget allocations.

50
b) Construct Bar Diagram

Aim:
Write a MATLAB program to Construct the Bar Diagram for the
given data = [10, 25, 15, 30, 20];
groupedData = [10, 25, 15, 30, 20; 15, 20, 10, 25, 18];
stackedData = [10, 25, 15, 30, 20; 15, 20, 10, 25, 18];
errorData = [10, 25, 15, 30, 20];
errors = [1, 2, 1.5, 3, 2];
data3D = rand(3, 4);

Software Required: MATLAB


Version: R2025a

Algorithm:

SStep 1: Start
Step 2: Create data, grouped data, stacked data(used for a stacked bar graph), errordata, errors,
data3D.
Step 3: Divides the figure into a 2x3 grid and subplots are used for bar graph types.
Step 4: Selects the first subplot for the regular bar graph. Creates a simple bar graph with data on
the y-axis. Adds labels and a title.
Step 5: Creates a grouped bar graph with each column representing a category and each bar
within a column representing a series. Add a legend to identify the series.
Step 6: Creates a stacked bar graph where bars from different series are stacked on top of each
other.
Step 7: Creates the base bar graph, allows multiple plots on the same axes, Add error bars to the
bar graph, Stops adding plots to the current axes.
Step 8: Creates a horizontal bar graph.
Step 9: Creates a 3D bar graph. Add labels for the x, y, and z axes.
Step 10: Stop

Program:

51
% Create sample data
data = [10, 25, 15, 30, 20];
groupedData = [10, 25, 15, 30, 20; 15, 20, 10, 25, 18];
stackedData = [10, 25, 15, 30, 20; 15, 20, 10, 25, 18];
errorData = [10, 25, 15, 30, 20];
errors = [1, 2, 1.5, 3, 2];
data3D = rand(3, 4);

% Regular Bar Graph


subplot(2, 3, 1)
bar(data);
xlabel('Categories');
ylabel('Values');
title('Regular Bar Graph');

% Grouped Bar Graph


subplot(2, 3, 2);
bar(groupedData);
xlabel('Categories');
ylabel('Values');
title('Grouped Bar Graph');
legend('Series 1', 'Series 2');

% Stacked Bar Graph


subplot(2, 3, 3);
bar(stackedData, 'stacked');
xlabel('Categories');
ylabel('Values');
title('Stacked Bar Graph');
legend('Series 1', 'Series 2');

% Bar Graph with Error Bars


subplot(2, 3, 4);
bar(errorData);
hold on;
errorbar(errorData, errors, 'r.', 'LineWidth', 1.5);
hold off;
xlabel('Categories');
ylabel('Values');
title('Bar Graph with Error Bars');

% Horizontal Bar Graph


subplot(2, 3, 5);
barh(data);
xlabel('Values');
ylabel('Categories');
title('Horizontal Bar Graph');

% 3D Bar Graph
52
subplot(2, 3, 6);
bar3(data3D);
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Values');
title('3D Bar Graph');

Output:

PARTICULARS MARKS ALLOTTED MARKS OBTAINED


Aim & Algorithm 5
Program 10
Output 5
Viva Voce 5
Total 25

Result:
Hence, the program to Construct the Bar Diagram has been completed successfully.

53
Application
Pie Chart – Application

A company tracks website traffic from 4 sources over a week:

Source Visitors

Direct 300

Referral 200

Social Media 150

Search Engine 350


Show the percentage share of each traffic source visually using a pie chart.

Step-by-Step Solution:
1. Total visitors = 300 + 200 + 150 + 350 = 1000
2. Calculate percentages:

Source % Visitors

Direct 30%

Referral 20%

Social Media 15%

Search Engine 35%

3. Plot a pie chart based on % values.


Use:
 Marketing teams analyze traffic sources
Resource allocation (how much to invest in each channel)

MATLAB Code – Pie Chart


% Data
visitors = [300, 200, 150, 350];
sources = {'Direct', 'Referral', 'Social Media', 'Search Engine'};

% Create Pie Chart


figure;
pie(visitors, sources);
title('Website Traffic Source Distribution');

54
Output:

Bar Chart – Application


A system administrator records the number of server errors per day over a week:

Day Errors
Mon 5
Tue 8
Wed 2
Thu 6
Fri 9
Sat 3
Sun 1

Step-by-Step Solution:
1. Organize data (Days, Errors)
2. Use a bar chart to visually show which days had more errors.
3. Use this to identify trends (e.g., higher errors on workdays).
Use:
 System reliability analysis
 Predictive maintenance planning

MATLAB Code – Bar Chart


% Data
days = {'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'};

55
errors = [5, 8, 2, 6, 9, 3, 1];

% Create Bar Chart


figure;
bar(errors);
set(gca, 'XTickLabel', days);
xlabel('Day of the Week');
ylabel('Number of Errors');
title('Server Errors per Day');
grid on;
Output:

Inference:

A bar diagram (or bar chart) is a graphical representation of categorical data using
rectangular bars, where the length or height of each bar is proportional to the value or frequency of
the category it represents. Bar diagrams can be vertical or horizontal and are widely used to
compare different groups or track changes over time, making complex data easier to understand
through a clear and visual summary of distributions and relationships.

EX.NO:9
TO FIND CORRELATION COEFFICIENT
DATE

56
To find correlation coefficient

Aim:
Write a MATLAB program to find correlation coefficient for the given data
x = [65, 66, 67, 67, 68,69,70,72];
y = [67, 68, 65, 68, 72, 72, 69,71];

Software Required: MATLAB


Version: R2025a

Algorithm:
Step 1: Start
Step 2: Initialize x and y as two datasets. x contains the values [65, 66, 67, 67, 68,69,70,72],
and y contains the values [67, 68, 65, 68, 72, 72, 69,71].
Step 3: To compute the correlation coefficient matrix R for the datasets x and y,
the corrcoef function is used. This matrix contains the correlation coefficients between
each pair of the input vectors. In this case, it will be a 2x2 matrix where:
 R(1, 1) is the correlation of x with itself,
 R(2, 2) is the correlation of y with itself,
 R(1, 2) (and R(2, 1)) is the correlation between x and y.
Step 4: The correlation coefficient between x and y is extracted from the matrix R using R(1,
2) and stored in the variable correlation coefficient.
Step 5: Print the value of the correlation coefficient, indicating the strength and direction of the
linear relationship between x and y.
Step 6: Stop.

Program:
% Example datasets
x = [65, 66, 67, 67, 68,69,70,72];
y = [67, 68, 65, 68, 72, 72, 69,71];

% Calculate the correlation coefficient


57
correlation_coefficient = corr(x', y');

% Display the result


disp(['Correlation Coefficient: ', num2str(correlation_coefficient)]);

% Plot the data


figure;
scatter(x, y, 'bo', 'filled');
hold on;

% Enhance plot
title(['Scatter Plot with Correlation Coefficient: ', num2str(correlation_coefficient)]);
xlabel('x');
ylabel('y');
grid on;
hold off;

Output:

x = [65, 66, 67, 67, 68,69,70,72] x = [10, 20, 30, 40, 50, 60, 70, 80]
y = [67, 68, 65, 68, 72, 72, 69,71] y = [15, 25, 35, 45, 55, 65, 75, 85]

x = [5, 10, 15, 20, 25, 30, 35, 40];


y = [40, 38, 34, 30, 26, 22, 18, 14];

58
PARTICULARS MARKS ALLOTTED MARKS OBTAINED
Aim & Algorithm 5
Program 10
Output 5
Viva Voce 5
Total 25

Result:
Hence, the program to find correlation coefficient has been completed successfully.

Application

Correlation between Working Hours and Task Completion

59
An IT manager wants to know whether there's a relationship between the number of hours developers
work per day (x) and the number of tasks they complete (y).
Given Data:
Developer Hours Worked (x) Tasks Completed (y)
A 6 5
B 7 6
C 5 4
D 8 8
E 9 9

Step 1: Create Table with Required Values

x y x² y² xy
6 5 36 25 30
7 6 49 36 42
5 4 25 16 20
8 8 64 64 64
9 9 81 81 81
2 2
∑ x=35 , ∑ y=32 , ∑ x =255 , ∑ y =222 , ∑ xy=237
Step 2: Use the Formula
n ∑ xy −∑ x ∑ y
r=
√¿¿ ¿
n=5
5( 237)−(35)(32)
r=
√¿ ¿ ¿
65 65 65
r= = ≈ ≈ 0.9912
√ 50 ⋅86 √ 4300 65.574
✅ Very Strong Positive Correlation between working hours and tasks completed.
MATLAB Code
% Data
x = [6, 7, 5, 8, 9]; % Hours Worked
y = [5, 6, 4, 8, 9]; % Tasks Completed

% Pearson Correlation Coefficient


r = corrcoef(x, y);
disp('Correlation Coefficient Matrix:');
disp(r);

% Plot
figure;
scatter(x, y, 'filled');
xlabel('Hours Worked');
ylabel('Tasks Completed');

60
EX.NO:10
DATE: TO FIND REGRESSION LINE

title('Correlation between Hours Worked and Tasks Completed');


grid on;

% Regression Line
hold on;
coeffs = polyfit(x, y, 1);
y_fit = polyval(coeffs, x);
plot(x, y_fit, '--r');
legend('Data Points', 'Best Fit Line');
Output:

Conclusion
 The correlation coefficient r ≈ 0.9912 shows a very strong positive linear relationship.
 This helps IT managers predict productivity based on working hours.

Inference:
Correlation is a statistical measure that expresses the extent to which two variables are linearly
related. It quantifies the strength and direction of the relationship, ranging from -1 (perfect negative
correlation) to +1 (perfect positive correlation), with 0 indicating no linear association. Correlation helps
identify if increases in one variable are associated with increases or decreases in another, making it
essential in data analysis, finance, psychology, and many IT applications for understanding dependencies
without implying causation.

To find regression line


61
Aim:
Write a MATLAB program to find regression line for the given data
x = [1, 2, 3, 4, 5];
y = [1.1, 1.9, 3.2, 3.8, 5.1];
.
Software Required: MATLAB
Version: R2025a

Algorithm:

Step 1: Start
Step 2: Define two arrays, x and y, which represent the independent and dependent
variables, respectively.
Step 3: n is calculated as the number of data points using the length function.
Step 4: Several sums are computed:
 sum_x: Sum of all x values.
 sum_y: Sum of all y values.
 sum_xy: Sum of the product of corresponding x and y values.
 sum_x2: Sum of the squares of x values.
Step 5: The slope (a) and intercept (b) of the regression line (in the form (y=ax+b)) are
calculated using the least squares method.
Step 6: display the regression equation.
Step 7: A regression line is plotted using the calculated coefficients over a range of x
values.
Step 8: The axes are labeled, a title is added, and a grid is displayed for better readability.
Step 9: To stop adding to the current plot, allowing for new plots to be created in the future
without overlapping.
Step 10: Stop.

Program:

% Example data points (x, y)


x = [1, 2, 3, 4, 5];
y = [1.1, 1.9, 3.2, 3.8, 5.1];

% Calculate the number of data points


n = length(x);

62
% Calculate necessary sums
sum_x = sum(x);
sum_y = sum(y);
sum_xy = sum(x .* y);
sum_x2 = sum(x.^2);
% Calculate coefficients of the regression line (y = a*x + b)
a = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x^2);
b = (sum_y - a * sum_x) / n;
% Display the coefficients
fprintf('Regression line equation: y = %.4fx + %.4f\n', a, b);

% Plot the data points


scatter(x, y, 'filled');
hold on;

% Plot the regression line


x_fit = linspace(min(x), max(x), 100);
y_fit = a * x_fit + b;
plot(x_fit, y_fit, 'r', 'LineWidth', 2);

% Add labels and title


xlabel('X');
ylabel('Y');
title('Linear Regression');

% Display grid
grid on;

% Hold off from further plotting


hold off;
Output:

(i) x = [1, 2, 3, 4, 5]; (ii) x = [10, 20, 30, 40, 50]


y = [1.1, 1.9, 3.2, 3.8, 5.1] y = [12.2, 19.5, 29.1, 40.3, 52.6]
Regression line equation: y = 0.9900x + 0.0500 Regression line equation: y = 0.9900x + 0.0500

63
PARTICULARS MARKS ALLOTTED MARKS OBTAINED
Aim & Algorithm 5
Program 10
Output 5
Viva Voce 5
Total 25

Result:
Hence, the program to find regression line has been completed successfully.
Application

Regression is a statistical method to model the relationship between a dependent variable (output) and one or more
independent variables (inputs).
 Simple Linear Regression fits a straight line:
y=a+bx
Where:
 y = predicted output (dependent variable)
 x = input (independent variable)
 a = intercept
 b = slope (regression coefficient)

Predicting Task Completion from Hours Worked

If a developer works 7.5 hours, how many tasks can we predict they will complete?
Given Data:
Developer Hours Worked (x) Tasks Completed (y)
A 6 5
64
Developer Hours Worked (x) Tasks Completed (y)
B 7 6
C 5 4
D 8 8
E 9 9

Step 1: Compute the Regression Coefficients


We use:
n ∑ xy−∑ x ∑ y
b= 2
n ∑ x −¿ ¿
∑ y−b ∑ x
a=
n
From earlier:
 ∑ x=35
 ∑ y=32
 ∑ xy=237
 ∑ x 2=255
 n=5
5 ⋅237−35 ⋅32 1185−1120 65
b= = = =1.3
5 ⋅255−35
2
1275−1225 50
32−1.3 ⋅35 32−45.5 −13.5
a= = = =−2.7
5 5 5
✅ Regression Equation:
y=−2.7+1.3 x
Step 2: Make a Prediction
If x = 7.5 hours, then
y=−2.7+1.3 ⋅7.5=−2.7+9.75=7.05
📌 Predicted Tasks Completed = 7.05

MATLAB Code
% Data
x = [6, 7, 5, 8, 9]; % Hours Worked
y = [5, 6, 4, 8, 9]; % Tasks Completed

% Regression Coefficients
p = polyfit(x, y, 1); % p(1) = slope (b), p(2) = intercept (a)
fprintf('Regression Equation: y = %.2f + %.2fx\n', p(2), p(1));

% Prediction for x = 7.5


x_pred = 7.5;
y_pred = polyval(p, x_pred);
fprintf('Predicted Tasks for %.1f hours = %.2f\n', x_pred, y_pred);

% Plot
figure;
scatter(x, y, 'filled');
hold on;
y_fit = polyval(p, x);
plot(x, y_fit, '--r', 'LineWidth', 2);
65
xlabel('Hours Worked');
ylabel('Tasks Completed');
title('Linear Regression: Hours vs Tasks');
legend('Data Points', 'Regression Line');
grid on;

Output:

Conclusion
 The regression equation helps predict output (tasks) based on input (hours worked).
You can apply this method to many IT scenarios: bug reports vs. hours, server load vs. request rate, or network
speed vs. packet size.

Inference:

Regression is a statistical method used to examine and model the relationship between a
dependent variable and one or more independent variables. It helps predict how changes in the
independent variables influence the dependent variable, allowing analysts to understand patterns and make data-

66
driven decisions. Widely used in fields like machine learning, finance, and business analytics, regression simplifie
complex relationships into equations or models that inform forecasting, optimization, and causal analysis.

Content Beyond the syllabus

To find the Binomial Distribution


Aim:
In a given experiment, a coin is flipped 10 times, and the probability of getting heads (success) on each
flip is 0.5. write MATLAB program simulates the number of successes in these trials using a binomial
distribution with parameters n=10 and p=0.5. It generates 1000 random samples from the binomial
distribution, calculates the probability of obtaining exactly 5 successes, and visualizes the theoretical
probability mass function (PMF) alongside a histogram of the generated samples.
Program:
% Parameters for the binomial distribution
n = 10; % Number of trials
p = 0.5; % Probability of success in each trial

% Generate random samples from the binomial distribution


num_samples = 1000;
samples = binornd(n, p, [1, num_samples]);

% Calculate the probability of getting a specific number of successes


k = 5; % Number of successes
probability_k_successes = binopdf(k, n, p);
fprintf('Probability of getting %d successes in %d trials: %.4f\n', k, n, probability_k_successes);

% Plot the binomial distribution


x = 0:n; % Number of successes (0 to n)
y = binopdf(x, n, p); % Binomial probability mass function

figure;
bar(x, y, 'FaceColor', [0.2 0.6 0.5]);
hold on;

% Overlay the histogram of the generated samples


histogram(samples, 'Normalization', 'pdf', 'FaceColor', [0.6 0.2 0.5], 'EdgeColor', 'none', 'FaceAlpha', 0.5);

xlabel('Number of Successes');
ylabel('Probability');
title(['Binomial Distribution (n = ', num2str(n), ', p = ', num2str(p), ')']);
legend('Theoretical PMF', 'Sampled Data');
hold off;

Output:

67
Result: Probability of getting 5 successes in 10 trials: 0.2461.

Application
Network Packet Transmission
The Binomial Distribution models the number of successes in a fixed number of independent trials,
each with the same probability of success.

k ()
P( X=k )= n p ¿
k

Where:

68
 n = number of trials
 k = number of successes
 p = probability of success
 1− p = probability of failure

 ( nk) = combinations (n choose k)


Case Study:
 A server transmits 10 data packets.
 Each packet has a 95% chance of being received correctly.
 What's the probability that exactly 9 packets are received correctly?
Given:
 n=10, k =9, p=0.95

( )
P( X=9)= 10 ⋅ ¿
9

¿ 10 ⋅(0.6302)⋅(0.05)=10⋅ 0.03151=0.3151
✅ So, the probability is 0.3151 (≈ 31.5%) that exactly 9 packets are received correctly.
MATLAB Code
% Parameters
n = 10; % number of trials, p = 0.95; % probability of success
k = 0:n; % number of successes % Custom Binomial PMF (no toolbox needed)
prob = arrayfun(@(x) nchoosek(n, x) * p^x * (1 - p)^(n - x), k);
% Display probability of exactly 9 successes
fprintf('P(X = 9) = %.4f\n', prob(10)); % 10th element is for k=9
% Plot
figure;
bar(k, prob, 'FaceColor', [0.2 0.6 0.8]);
xlabel('Number of Successful Packets');
ylabel('Probability');
title('Binomial Distribution: Packet Success (n = 10, p = 0.95)');
grid on;
Output:

69
Conclusion:
The Binomial distribution helps in:
 Predicting success counts (like received packets, correct logins).
 Modeling yes/no experiments with fixed trials.
 IT quality control, security, and data transmission reliability.

Inference:
The binomial distribution is a discrete probability distribution that models the number of successes
in a fixed number of independent trials, where each trial has exactly two possible outcomes: success or
failure. It is defined by two parameters: nn (number of trials) and pp (probability of success), and is
widely used to calculate the probability of obtaining a certain number of successes in various fields such
as quality control, survey analysis, and risk assessment. The distribution assumes independent trials with a
constant probability of success, making it a fundamental tool for modeling binary events and decision-
making processes.

(ii) To find the Poisson distribution


AIM:
Consider a call center where the average number of calls received per hour is 5. Write a MATLAB
program simulates the call arrival process using a Poisson distribution with an average rate of 5 calls per
hour. It generates 1000 random samples from the Poisson distribution, calculates the probability of
receiving exactly 3 calls in an hour, and plots the Poisson distribution alongside a histogram of the
generated data.

Program:
% Parameters for the Poisson distribution
lambda = 5; % Average number of events (calls per hour)

% Generate random samples from the Poisson distribution


num_samples = 1000;
samples = poissrnd(lambda, [1, num_samples]);

% Calculate the probability of getting exactly k events (3 calls)


k = 3;
probability_k_calls = poisspdf(k, lambda);
fprintf('Probability of receiving exactly %d calls in an hour: %.4f\n', k, probability_k_calls);

70
% Plot the Poisson distribution
x = 0:max(samples); % Number of events (0 to max observed in samples)
y = poisspdf(x, lambda); % Poisson probability mass function

figure;
bar(x, y, 'FaceColor', [0.2 0.6 0.5]);
hold on;

% Overlay the histogram of the generated samples


histogram(samples, 'Normalization', 'pdf', 'FaceColor', [0.6 0.2 0.5], 'EdgeColor', 'none', 'FaceAlpha', 0.5);

xlabel('Number of Calls');
ylabel('Probability');
title(['Poisson Distribution'])

Output:

Result:
Probability of receiving exactly 3 calls in an hour: 0.1404

71
Application
Server Requests per Minute
The Poisson distribution models the number of times an event occurs in a fixed interval of time or
space, when:
 Events occur independently
 At a constant average rate λ
Two events cannot happen at the exact same instant
Formula:
−λ k
e λ
P( X=k )=
k!
Where:
 λ = average number of events per interval
 k = actual number of events
 e ≈2.71828

Case Study:
Suppose a web server receives on average 5 requests per minute. What’s the probability that exactly 3
requests occur in a given minute?
Given:
 λ=5, k =3
−5 3
e ⋅5 0.0067 ⋅125 0.8375
P( X=3)= = = ≈ 0.1396
3! 6 6
✅ So, the probability is ≈ 13.96%
MATLAB Code
% Parameters
lambda = 5; % Average number of requests per minute
k = 0:10; % Number of requests (0 to 10)
% Custom Poisson PMF
prob = exp(-lambda) .* (lambda .^ k) ./ factorial(k);
72
% Display probability of exactly 3 requests
fprintf('P(X = 3) = %.4f\n', prob(4)); % MATLAB indexing starts at 1
% Plot the distribution
figure;
stem(k, prob, 'filled', 'MarkerSize', 4, 'LineWidth', 1.5);
xlabel('Number of Server Requests');
ylabel('Probability');
title('Poisson Distribution: Web Requests per Minute (\lambda = 5)');
grid on;
Output:

Inference:
The Poisson distribution is a discrete probability distribution that models the number of times an
event occurs within a fixed interval of time or space, given that these events happen independently and at
a constant average rate (λ). It is widely used in fields like telecommunications, traffic flow analysis, and
reliability engineering to predict event counts when the events are rare but potentially many, such as the
number of calls received by a call center or the arrival of packets in a network. The mean and variance of
the Poisson distribution are both equal to λ, capturing the expected frequency and variability of the events.

73

You might also like