Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Matelab 2

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

EC23102

DIGITAL SIGNAL PROCESSING

MATLAB PRACTICAL REPORT


SUBMITTED BY: -

Student Name: - Roll No: -


1.MINA NATH D/22/EC/205
2.EPIBENI B KION D/22/EC/203
3.YAITHOIBA LAISHRAM D/22/EC/206
4.S. RAIVEIKHO D/21/EC/103
5. ARKI KUPAR LYNGDOH
MAWPHLANG D/22/EC/204
6.JUTAN DAS D/22/EC/211

THE GUIDANCE OF
DR. MADHUSUDHAN MISRA
(Associate Professor)
NORTH EASTERN REGIONAL INSTITUTE OF SCIENCE AND
TECHNOLOGY

Dept. of Electronics and Communication Engineering


NORTH EASTERN REGIONAL INSTITUTE OF SCIENCE AND TECHNOLOGY
(Deemed University)
Nirjuli-791109, Arunachal Pradesh
EC23102
DIGITAL SIGNAL PROCESSING

Q1. MATLAB code to read and image and display its negative (inverted colour).

CODE

%Readtheimage
originalImage=imread('cameraman.tif');%Replace'your_image_filename.jpg'withthe
actualfilenameofyourimage

% Check if the image is RGB or


grayscaleifsize(originalImage,3)==3
%ForRGBimages negativeImage
= 255 -
originalImage;else %Forgrayscaleimages
negativeImage=255 -originalImage;
end

% Display the original and negative images side by


sidesubplot(1, 2,1); imshow(originalImage);tit
le('OriginalImage');
subplot(1, 2,
2);imshow(negativeImage);
title('NegativeImage');

% Display a common title for the


figuresgtitle('OriginalandNegativeImages
');

OUTPUT
EC23102
DIGITAL SIGNAL PROCESSING

Q2. MATLAB code to plot two function son the same graph with different lines style and colour.

CODE
%Generate values x=linspace(-2*pi,2*pi,100);

% Calculate y values for two


functionsy1 =sin(x); y2=cos(x);

% Plot the first function with a solid blue lineplot(x,y1,'b-


', 'LineWidth',2); hold on;%Holdthecurrentplot

% Plot the second function with a dashed red lineplot(x,y2,'r-


-','LineWidth', 2);

% Add labels and a legendxlabel('X-axis');


ylabel('Y-axis');title('Plotting
Two
Functions');legend('sin(x)','cos
(x)');

% Display the gridgrid


on;

% Release the plot holdhold


off;

OUTPUT
EC23102
DIGITAL SIGNAL PROCESSING

Q3. MATLAB code to plot a sine wave.

CODE
% Generate x values from 0 to
2*pix= linspace(0,2*pi,100);

% Calculate y values for the sine wavey


=sin(x);
%Plotthesinewave
plot(x,y,'b-','LineWidth',2);
% Add labels and
titlexlabel('X-axis');
ylabel('Yaxis');title('Sine
WavePlo t'); % Display the
gridgrid on;

OUTPUT
EC23102
DIGITAL SIGNAL PROCESSING

Q4. MATLAB code to plot a bar graph for the give data.

CODE

%Given data
x= [1,2, 3,4, 5];
y=[10,24,17,20,15];
% Plot a bar graph
bar(x,y,'b');
% Add labels and
titlexlabel('X-axis');
ylabel('Yaxis');
title('BarGraph');
% Display the
gridgrid on;

OUTPUT
EC23102
DIGITAL SIGNAL PROCESSING

Q5. MATLAB code to create a 3D plot of a sphere.

CODE
% Create a 3D plot of a sphere
figure;

% Set the radius of the sphere


radius =5;

% Use the sphere function to generate sphere


coordinates [sx, sy,sz]= sphere;
% Scale the sphere coordinates by the radius
sx=radius*sx;
sy = radius * sy;
sz =radius*sz;
%Plot the sphere
Surf (sx, sy, sz,'FaceAlpha',0.5,'EdgeColor','none');
% Add labels and titlexlabel('X-
axis'); ylabel('Y-axis');
zlabel('Z-axis');
title('3DPlotofaSphere');
% Set aspect ratio to be equal for
all axes axis equal;
% Display the gridgrid
on;

OUTPUT
EC23102
DIGITAL SIGNAL PROCESSING

Q6. MATLAB code to generate a 5x5 matrix with values from 1 to25.

CODE
%Set the size of the matrix matrixSize=5;

% Generate a 5x5 matrix with values from 1 to 25 in a checkerboard

patterncheckerboardMatrix=reshape(1:matrixSize^2,matrixSize, matrixSize);

% Display the checkerboard matrixdisp('Checkerboard

Matrix:'); disp (checker board Matrix

);

OUTPUT
EC23102
DIGITAL SIGNAL PROCESSING

Q7. MATLAB code to calculate a factorial of a number provided by user.

CODE
%Prompt the user for input
num=input ('Enter a non-negative integer r to calculate its factorial:');

%Check if the input is a non-negative integer


If is numeric(num)&& is scalar(num)&&num>=0&&mod (num, 1)==0
%In it realize the factorial result
Factorial Result=1;

%Calculate the factorial using a loop for


i =1:num factorial Result=factorial Result*i;
end

%Display the result


Fprintf ('The factorial of %d is %d\n', num,
Factorial Result);
else
%Display an error message for invalid input disp ('Invalid input. Please enter
a non-negative integer.');
end
OUTPUT

Q8. Load as ample image, convert it to grayscale, and apply a Gaussian blur to the image
using a custom convolution kernel.
CODE
%Load as ample image
originalImage=imread('peppers.png');
%Replace' peppers. png 'with the actual file name of y our image

% Convert the image to grayscale if it is an RGB image


if size(originalImage,3) ==3
gray Image=rgb2gray(originalImage);
else gray Image=originalImage;
end

% Display the original and grayscale


images figure; subplot(1, 2,
1);
imshow(originalImage);
title('OriginalImage');
EC23102
DIGITAL SIGNAL PROCESSING

subplot(1, 2,
2); imshow (gray Image);
title ('Grayscale Image');

% Define a custom Gaussian blur


kernel sigma =2;
kernelSize=6*sigma;
gaussianKernel=fspecial('gaussian',[kernelSize, kernelSize],sigma);

%ApplyGaussianblurtothegrayscaleimage
blurredImage=imfilter(grayImage,gaussianKernel,'conv','replicate');

% Display the blurred imagefigure;imshow(blurredI


mage);title('BlurredImage')
;

OUTPUT

Q9 Define two variables a and b with values 5 and 8, respectively. Calculate and display their sum.

CODE
% Define two variables a and
ba =5; b = 8;

% Calculate the sum of a and bsum_result


=a+ b;

%Displaytheresult
fprintf('Thesumof%dand%dis:%d\n',a,b,sum_result);

OUTPUT
EC23102
DIGITAL SIGNAL PROCESSING

Q10.Plot the functions y = x^2 and y = 2x on the same graph. Add a legend and title to the plot.
CODE
%Generatexvalues x=linspace(-5,5,100);

% Calculate y values for the


functionsy1 =x.^2; y2=2*x;

% Plot the functionsfigure;


plot(x, y1, 'b-', 'LineWidth', 2, 'DisplayName', 'y = x^2');hold
on;%Hold thecurrentplot
plot(x,y2,'r--','LineWidth',2,'DisplayName','y=2x');

% Add legend, labels, and


titlelegend('Location', 'Northwest');xlabel('X-
axis'); ylabel('Y-axis');
title('Plotofy=x^2andy=2x');

% Display the gridgrid


on;

% Release the plot holdhold


off;

Q11. MATLAB code to implement a wiener filter to reduce noise in a signal or


EC23102
DIGITAL SIGNAL PROCESSING

imageCODE
%Generate a signal and a template (matched filter)
signal=randn (1,100); %Example signal (replace with your
signal)
template=fliplr(signal); %Matchedfiltertemplateisthetime-reversedsignal
%Applythematchedfilter
filteredSignal=conv(signal,template,'full');

% Plot the original signal, matched filter template, and filtered signal
figure;
subplot (3, 1,
1); plot(signal); title ('Or
iginalSignal');
subplot (3, 1, 2);
plot(template)
;
title('MatchedFilterTemplate');

Q12.MATLAB code to apply a convolution al gorithtoen hance their solution of an image

CODE
%Readanexampleimage

originalImage=imread('cameraman.tif'); %Replacewiththeactualimagefile

% Define a kernel (point spread function) for


blurringkernelSize =5;
blurKernel=fspecial('gaussian’, [kernelSize,kernelSize],2);
EC23102
DIGITAL SIGNAL PROCESSING

%Blurtheimagewiththedefinedkernel
blurredImage=imfilter(originalImage, blurKernel,'conv','circular');

%Addsomenoisetotheblurredimage
noisyBlurredImage=imnoise(blurredImage,'gaussian',0,0.01);

% Apply Wiener deconvolution to enhance the


resolutionestimatedImage=deconvwnr(noisyBlurredImage,blurKernel,
0.01);

% Display the original, blurred, noisy, and deconvolved


imagesfigure;
subplot(2, 2,
1);imshow(originalImage)
;title('OriginalImage');
subplot(2, 2,
2);imshow(blurredImage)
;title('BlurredImage');
subplot(2, 2,
3);imshow(noisyBlurredImage);title
('NoisyBlurredImage');
subplot(2, 2,
4);imshow(estimatedImage);title('Decon
volvedImage');

Q12.MATLAB code to apply a convolutional gorithtoen hance their solution of an image

CODE
% Generate a signal with noiset=linspace
(0, 1,1000); signal= sin (2*pi*5* t)
+0.5*randn(size(t));

%Addmorenoisetothesignal
signalWithNoise=signal+0.5*randn(size(t));

% Apply Wiener filter for noise


EC23102
DIGITAL SIGNAL PROCESSING

reductionfilteredSignal=wiener2(signalWithNoise,[5,5])
;

% Plot the original signal, signal with noise, and filtered


signalfigure;
subplot (3,1,1); plot (t,
signal); title
('OriginalSi gnal');
subplot (3,1,2); plot
(t,sig nalWithNoise);
title('SignalwithNoise');
subplot (3,1,3); plot (t,
filteredSignal); title
('Fi lteredSignal');

Q13.ImplementtheBisectionmethodto findtherootofa givenfunctionwithinaspecifiedinterval.

CODE
%Generateasignalandatemplate(matchedfilter)
signal=randn(1,100);%Examplesignal(replacewithyoursignal)
template=fliplr(signal);%Matchedfiltertemplateisthetime-reversedsignal
%Addnoisetothesignal
noisySignal=signal+0.5*randn(size(signal));

%Applythematchedfilter
filteredSignal=conv(noisySignal,template,'full');
EC23102
DIGITAL SIGNAL PROCESSING

% Plot the original signal, matched filter template, noisy signal, and
filteredsignal figure;
subplot(4, 1,
1);plot(signal);title('Or
iginalSignal');
subplot(4, 1,
2);plot(template)
;
title('MatchedFilterTemplate');
subplot(4, 1,
3);plot(noisySignal);t
itle('NoisySignal');
subplot(4, 1,
4);plot(filteredSignal);t
itle('FilteredSignal');

%Highlightthedetectionpoint [maxValue,
maxIndex] = max(filteredSignal);hold
on;
plot(maxIndex, maxValue, 'ro', 'MarkerSize',
10);hold off;

Q14.MATLABcodeto usefouriertransformtoanalyzethefrequencycontentofthe original image,


andfilteredimages.Visualizethefrequencyspectra

% Load a grayscale image (replace with your own

image)imageData= imread('cameraman.tif');

% Implement a custom filter/kernel (e.g., an edge detection


filter)filterSize =5;
edgeFilter = -ones(filterSize) /
(filterSize^2);edgeFilter(floor(filterSize/2)+1,floor(filterSize/2)+1)=filterSi
ze^2-1;

%Applythecustomfilterusingconvolution
filteredImage=conv2(double(imageData),edgeFilter,'same');

% Visualize the original image, custom filter, and filtered


imagefigure;
EC23102
DIGITAL SIGNAL PROCESSING

subplot(2, 3,
1);imshow(imageData);tit
le('OriginalImage');
subplot(2, 3,
2);imshow(edgeFilter,
[]);title('CustomFilter
');
subplot(2, 3,
3);imshow(filteredImage,
[]);title('FilteredImage')
;

% Compute and visualize the frequency spectra using


FFToriginalSpectrum =
fftshift(fft2(imageData));filteredSpectrum=fftshift(fft
2(filteredImage));
subplot(2,3,4);
imagesc(log(abs(originalSpectrum) +
1));title('OriginalImageSpectrum');
subplot(2,3,5);
imagesc(log(abs(filteredSpectrum) +
1));title('FilteredImageSpectrum');
colormapjet;
% Display colorbarh = colorbar;
set(h,'Position',[0.920.10.020.8]);

%Adjustthelayout
sgtitle('ImageandFrequencySpectraVisualization');
Q15.MATLABcodetoImplementamethodtovisualize theoriginal image,thecustomfilter, andthe
resultofthefilteringprocess.

% Load a grayscale image (replace with your own


image)imageData= imread('cameraman.tif');

% Implement a custom filter/kernel (e.g., an edge detection


filter)filterSize =5;
edgeFilter = -ones(filterSize) /
(filterSize^2);edgeFilter(floor(filterSize/2)+1,floor(filterSize/2)+1)=filterSi
ze^2-1;

%Applythecustomfilterusingconvolution
filteredImage=conv2(double(imageData),edgeFilter,'same');

% Visualize the original image, custom


filter, and filtered imagefigure;
subplot(1, 3,
1);imshow(imageData);tit
le('OriginalImage');
subplot(1, 3,
2);imshow(edgeFilter,
[]);title('CustomFilter
');
subplot(1, 3,
3);imshow(filteredImage,
[]);title('FilteredImage')
;
EC23102
DIGITAL SIGNAL PROCESSING

sgtitle('OriginalImage,CustomFilter,andFilteredImageVisualization');

Q16MATLABcode tovisualize theoriginal image,thecustom filter, andtheresult offiltering.

% Load a grayscale image (replace with your own image)


imageData= imread('cameraman.tif');

%Implementacustomfilter/kernel (e.g., anedgedetectionfilter)filterSize


=5;
edgeFilter = -ones(filterSize) /
(filterSize^2); edgeFilter(floor(filterSize/2)+1,floor(filterSize/2)+1)=filterSi
ze^2-1;

%Applythecustomfilterusingconvolution
filteredImage=conv2(double(imageData),edgeFilter,'same');

% Visualize the original image, custom filter, and filtered


imagefigure;

% Display the original imagesubplot(2,


3, 1);imshow(imageData);title('
OriginalImage');

% Display the custom filtersubplot(2,


3, 2);imshow(edgeFilter,
[]); title('CustomFilter');

% Display the filtered


imagesubplot(2, 3,
3);imshow(filteredImage,
[]); title('FilteredImage');
EC23102
DIGITAL SIGNAL PROCESSING

% Display colorbarh
= colorbar;
set(h,'Position',[0.920.10.020.8]);

% Compute and display the histograms of the original and filtered


imagessubplot(2, 3,4); imhist(imageData);
title('OriginalImageHistogram');
subplot(2,3,5);
imhist(uint8(filteredImage));%Convertbacktouint8forimhisttitle('
FilteredImageHistogram');

% Display colorbarh
= colorbar;
set(h,'Position',[0.920.10.020.8]);

%Adjustthelayout
sgtitle('Image,CustomFilter,FilteredImage,andHistograms Visualization');

Q17.MATLABcodeImplement anon-linear regression model on experimental data and analyse the


modelfit.

CODE
%Generate synthetic data for demonstrationrng
(42); %S etseedforreproducibility x=linspace
(0,10,100)'; y=2*sin (1.5*x)
+0.5*randn(size(x));

% Define a non-linear model


functionmodelFun=@ (b, x) b (1) *sin (b (2) *x);

% Initial parameter guessinitialGuess=


[1,1];

%Fitthenon-linearmodeltothedata mdl=fitnlm(x,y,modelFun,initialGuess);

% Display the model parametersdisp('Fitted


Parameters:'); disp (mdl.Coefficients.Esti
mate);

% Plot the experimental data and the fitted modelfigure;


scatter (x, y, 'b', 'DisplayName', 'Experimental Data');
hold on;
xRange = linspace(min(x), max(x), 100);
yFit= predict(mdl,xRange);
plot (xRange, yFit, 'r', 'LineWidth', 2, 'DisplayName', 'Fitted
Model'); xlabel('X');
ylabel('Y');
title ('Non-linear Regression
Model Fit');
EC23102
DIGITAL SIGNAL PROCESSING

legend('Location','Best'); grid
on;holdoff
;

.
Q18.MATLABcodeSaveandloadvariables intheMATLABworkspace.

CODE
x = linspace (0, 10,
100); y =sin(x);
save('workspace.mat','x','y');

% Clear current workspaceclear;

%Loadvariablesfromsavedworkspaceload('wo
rkspace.mat');
disp('LoadedVariables:');
disp(['x:'num2str(x(1))'to'num2str(x(end))]);
disp(['y:'num2str(y(1))'to'num2str(y(end))]);

Q19. MATLAB code Perform symbolic mathematics.CODE


symsx;
EC23102
DIGITAL SIGNAL PROCESSING

expr = x^2 + 2*x + 1;


derivative = diff(expr);
integral=int(expr);
disp('Expression:');
disp(expr);
disp('Derivative:');
disp(derivative); disp
('I integral:');
disp(integral)
;

Q20.MATLABcodePerformPCAonadataset.

rng(42);%Set seed for reproducibility data =


randn(100, 3); % Example 100 data points in

3Dcoeff =pca(data);

disp ('Principal Components:');


disp(Coeff);

Q21.MATLABcodeCreatean animated plot of a sine wave.

CODE

t = linspace (0, 2*pi,


100); fig =figure;
fori=1: length(t) plot (t (1: i), sin (t
(1: i)), 'Linewidth',
2); xlabel('Time');
ylabel('sin(t)'); title ('Animated
Plot of sin(t)'); axis ([0,2*pi, -
1,1]); draw now; end
EC23102
DIGITAL SIGNAL PROCESSING

Q22.MATLABcode Generatethefirst10elementsoftheFibonaccisequence.

CODE
n = 10; fibonacci =
zeros (1, n);
fibonacci (1) = 0;
fibonacci (2) =1;
for i=3: n fibonacci(i)=fibonacci(i-1)
+fibonacci(i-2);
end
disp ('Fibonacci
Sequence:'); disp(fibonacci);

Q23. MATLAB code Generate a 3x3 matrix and perform basic matrix
operations.CODE

A = rand (3);
B=ey e (3);

C = A * B; % Matrix multiplicationD = A + B; %
Element-wise additionE=
A'%TransposeofmatrixA
disp ('Matrix A:');
disp(A); disp (
'Matrix B:');
disp(B); disp
('Matrix C (A *
B):'); disp(C); disp
('Matrix D (A +
B):'); disp(D);
disp ('Matrix E (Transpose of
EC23102
DIGITAL SIGNAL PROCESSING

A):'); disp(E);

Q24.MATLABcodePerformhistogram equalization on a gray scale image.

CODE

originalImage = imread('cameraman.tif'); equalized

Image=h isteq(originalImage);

figure;subplot(1, 2,1);
imshow(originalImage);ti
tle('OriginalImage');
subplot (1, 2, 2);
imshow(equalizedImage)
; title('EqualizedImage');
EC23102
DIGITAL SIGNAL PROCESSING

Q25.MATLABcodePerform linear regression on a set of data points.

CODE

x=linspace (0,10,20)'; y = 2 * x
+ 3 + 2 * randn(size(x)); mdl =
fitlm (x, y);

disp('Linear Regression
Coefficients:');disp(mdl.Coefficients.Es
timate);
figure;
scatter(x, y, 'b', 'DisplayName', 'Data
Points');hold on; plot(mdl);xl
abel('X'); ylabel('Y');
title('Linear Regression
Fit');legend('Location','Best')
;grid on; holdoff;
EC23102
DIGITAL SIGNAL PROCESSING

Q26.MATLABcodePerform anon-linearfitusingtheCurveFittingToolbox.

CODE

x=linspace(0,10,100)';
y=2*exp(-0.5*x)+0.2*randn(size(x));

%Createacustomnon-linearmodel
model=fittype('a*exp(-b*x)','independent','x','dependent','y');

% Fit the model to the dataoptions


=
fitoptions(model);options.Star
tPoint=[1,0.1];
fitResult=fit(x,y,model,options);

% Display the fitted parametersdisp('Fitted


Parameters:');disp(fitResult.a)
;disp(fitResult.b);

% Plot the experimental data and the fitted modelfigure;


scatter(x, y, 'b', 'DisplayName', 'Experimental Data');hold
on;
plot(fitResult, 'r', 'LineWidth', 2, 'DisplayName', 'Fitted
Model');xlabel('X'); ylabel('Y');
title('Non-linear Fit with Curve Fitting
Toolbox');legend('Location','Best');
grid on;holdoff
;
EC23102
DIGITAL SIGNAL PROCESSING

Q27.MATLAB code Solve a simple ordinary differential equation.

% Define the ODE: dy/dx = -


2yode = @(x,y)-2*y;

%SolvetheODE
[x,y]=ode45(ode,[0,5],1);
% Plot the solutionfigure;
plot(x, y, 'b', 'LineWidth',
2);xlabel('X'); ylabel('Y');
title('Solution of the ODE dy/dx = -
2y');grid on;
EC23102
DIGITAL SIGNAL PROCESSING

Q28.MATLAB code Simulate a 1D random walk.

nSteps=100;
positions=consume(randn(1,nSteps));
figure;
plot(1:nSteps, positions, 'b', 'Linewidth',
2);xlabel('Steps');
ylabel('Position'); title('1D
Random Walk
Simulation');grid on;
EC23102
DIGITAL SIGNAL PROCESSING

Q29.MATLABcode Create a simple GUI with uicontrol.

figure;
uicontrol('Style','text','String','Hello,MATLAB!','Position',[100,150,200,
30]);
uicontrol('Style', 'pushbutton', 'String', 'Click Me', 'Position', [150, 100,
100,30], 'Callback',@(src,event)disp('ButtonClicked!'));
title('SimpleGUIwithuicontrol');
EC23102
DIGITAL SIGNAL PROCESSING

Q30.MATLABcodeCreateananimated bargraph.

data=rand(1,10);
figure;bar (data);
xlabel('Category');ylabel('Val
ue');title('AnimatedBarGraph')
;
fori=1:50
data=rand(1,10);bar
(data);pause(0.1); end
EC23102
DIGITAL SIGNAL PROCESSING

Q31.MATLABcodePerform dataclusteringusingk-Means.

rng(42); % Set seed for reproducibilitydata=[randn(50,2);3+randn


(50,2)];
k = 2; % Number of
clustersidx=kmeans(data,k);
figure;
scatter(data(:,1),data(:,2),50,idx,'filled');
xlabel('Feature1'); ylabel('Feature
2');title('k-Means
Clustering');colormap(parula
(k));
EC23102
DIGITAL SIGNAL PROCESSING

Q32.MATLABcodePlotaparametric curve.

t = linspace(0, 2*pi,
100);x =cos(t); y=sin(t);
figure; plot(x, y, 'r',
'LineWidth', 2);xlabel('X');
ylabel('Y');
title('Parametric Curve:
Circle');axis equal; gridon;
EC23102
DIGITAL SIGNAL PROCESSING

Q33.MATLABcodeGenerateandplotafrequency-modulated(FM)signal.

fs = 1000; % Sampling
frequencyt=0:1/fs:1;%Timevector
f0=10;%Carrierfrequency kf = 5; % Frequency
deviation
constantfm_signal=cos(2*pi*f0*t+kf*sin(2*pi*

t));

figure;
plot(t, fm_signal, 'b', 'LineWidth',
2);xlabel('Time(s)');
ylabel('Amplitude'); title('Frequency
Modulated (FM)
Signal');grid on;
EC23102
DIGITAL SIGNAL PROCESSING

Q34.MATLABcodeCreatea 3Dscatterplot.

% Generate random datadata=randn(100,3);

figure;
scatter3(data(:, 1), data(:, 2), data(:, 3), 50,
'filled');xlabel('X');
ylabel('Y');
zlabel('Z'); title('3D
Scatter
Plot');grid on;
EC23102
DIGITAL SIGNAL PROCESSING

Q35.MATLABcodeRotateanimage.

% Load a sample image (replace with your own


image)originalImage= imread('peppers.png');

%Rotatetheimageby45degrees
rotatedImage=imrotate(originalImage,45,'bilinear','crop');
figure;subplot(1, 2,1);
imshow(originalImage);ti
tle('OriginalImage');
subplot(1, 2,
2);imshow(rotatedImage)
;title('RotatedImage');
EC23102
DIGITAL SIGNAL PROCESSING

Q36.MATLABcodeApplymorphologicaloperations toanimage.

% Load a binary image (replace with your own binary


image)binaryImage =imread('coins.png')>120;

%Performmorphologicaloperations dilatedImage =
imdilate(binaryImage, strel('disk',
5));erodedImage=imerode(binaryImage,strel('disk',5));
figure;subplot(1,
3,1);
imshow(binaryImage);title('Origina
lBinaryImage');
subplot(1, 3,
2);imshow(dilatedImage)
;title('DilatedImage');
subplot(1, 3,
3);imshow(erodedImage)
;title('ErodedImage');
EC23102
DIGITAL SIGNAL PROCESSING

Q37.MATLABcodeSimulate theLorenzsystem.

%DefineLorenzsystemequations
lorenzSystem = @(t, Y) [10*(Y(2) - Y(1)); Y(1)*(28 - Y(3)) - Y(2); Y(1)*Y(2)
8/3*Y(3)];

%Solvethesystemusingode45
[t,Y]=ode45(lorenzSystem,[0,30],[1,0,20]);

% Plot the simulation resultsfigure;


plot3(Y(:,1),Y(:,2),Y(:,3),'b','LineWidth',2);
xlabel('X'); ylabel('Y'); zlabel('Z');
title('Lorenz System Simulation');grid on;
EC23102
DIGITAL SIGNAL PROCESSING

Q38.MATLABcodeDesignandapply a low-passFIRfilter.

% Design a low-pass FIR filterfilterOrder


=30; cutoffFrequency=0.2;
firFilter = designfilt('lowpassfir', 'FilterOrder',
filterOrder,'CutoffFrequency',cutoffFrequency);

%Generateanoisysignal fs
= 1000; % Sampling
frequencyt =0:1/fs:2;
signal=sin(2*pi*50*t)+0.5*randn(size(t));

% Apply the FIR filter to the noisy


signalfilteredSignal=filter(firFilter,signal);

% Plot the original and filtered


signalsfigure;
subplot(2,1,1);plot(t,
signal);title('OriginalSi
gnal');
subplot(2,1,2);plot(t,
filteredSignal);title('Fi
lteredSignal');
EC23102
DIGITAL SIGNAL PROCESSING
EC23102
DIGITAL SIGNAL PROCESSING

Q39. MATLABc ode PerformaTaylorseriesexpansionforamathematica lfunction.

symsx;

% Define the function and point of


expansionf =exp(x); a = 0;

%CalculatetheTaylorseriesexpansion
taylorSeries=taylor(f,'Order',5,'ExpansionPoint',a);

%Displaytheresult disp('Taylor
Series
Expansion:');disp(taylorSeries);

% Plot the original function and its Taylor series


approximationfigure; fplot(f, 'b', 'DisplayName',
'exp(x)');hold on;
fplot(taylorSeries, 'r--', 'DisplayName', 'Taylor Series (Order
5)');xlabel('x');
ylabel('y'); title('Taylor
Series
Expansion');legend('Location','Be
st'); grid on;holdoff
;
EC23102
DIGITAL SIGNAL PROCESSING

Q40.MATLAB code Calculate and plot the Laplace transform o fa function.

symsts;
% Define a function
f=heaviside
(t);

% Calculate the Laplace transform


F = laplace (f, t, s);

% Display the result disp


('Laplace Transform:');
disp(F);

% Plot the original function and its Laplace


transform figure; subplot (2,1,1); ez plot
(f, [0, 5]);
title ('Original
Function');
grid on;
subplot (2,1,2); ez
plot (F, [0, 5]);
title ('Laplace
Transform');
grid on;
EC23102
DIGITAL SIGNAL PROCESSING

Practical: 1
% Simple mirror FIR
% a second FIR filter is obtained by sign alternation
h0=[1 3 1 4 1 3 1];
%original filter with symmetrical coeffs.
h1=[1 -3 1 -4 1 -3 1]; %a second filter is obtained.
w=0:(2*pi/511): pi;

H0=abs(fft(h0,512)); %discrete Fourier transform


H1=abs(fft(h1,512)); %discrete Fourier
transform plot (w, H0(1:256),'kx');
hold on;
plot (w, H1(1:256),'k');
axis ([0 pi 0 16]);
title ('frequency response (magnitude)');
xlabel('w');

Practical: 2
% Fourier transform %
a square
fg=ones (256,256); %white plane fg
(64:192, 64:192) =0; %insert black square
Ffg=fftshift(fft2(fg)); %Fourier
transform M=max (max (Ffg)); % the one
maximum value sFfg=(256*Ffg/M);
%normalization figure (1) subplot (1,2,1)
imshow(fg); %plots the binary image
title ('Fourier transform of a
square'); ylabel('original'); subplot
(1,2,2)
imshow(abs(sFfg)); %plots the Fourier transform ylabel('transform');
EC23102
DIGITAL SIGNAL PROCESSING

Practical: 3
%A simple symmetrical filter %
using polar coordinates
figure(1) xo=0; yo=0; zso=0; for
R=0:0.1:5, zs=sin(R*pi/5); for
nang=0:2:358,
phi=(nang*2*pi)/360; cg=0; if
zs>0, cg=1; end; clr=[zs,(1-
zs),zs]; %color coding
x=R*cos(phi); y=R*sin(phi);
plot3([xo x],[yo y],[zso zs],'Color',clr); hold on;
xo=x; yo=y; zso=zs; view(20,50);
end; end; title('Symmetrical
filter') xlabel('X');
ylabel('Y');

Practical : 4
% phase of pure time delay Td=2; %time delay
in seconds w=0.1:0.1:100;
%frequency data set in rad/s
phased=-Td*w;
%phase induced by time delay
plot (w, phased, 'k');
%plots phased vs. w
title ('phase caused by a delay of 2
seconds');
EC23102
DIGITAL SIGNAL PROCESSING

xlabel('rad/s');
ylabel('radians');
%taking last part of the phase line:
dtangent=(phased (1000)-phased (100))/(w
(1000)-w (100)); eTd=-dtangent; %Td estimate
eTd %result display

Practical: 5
% noise and pure time delay
Td=2; %time delay in seconds
%input signal fs=20; %sampling frequency in Hz
tiv=1/fs; %time interval between samples;
tu=0: tiv:(60-tiv);
%time intervals set (60 seconds)
Nu=length(tu); %number of data points
u=randn (Nu,1);
%random input signal data set
%output signal
NTd=Td*fs;
%number of samples along Td
Ny=Nu+NTd; y=zeros (1, Ny);
y((NTd+1): Ny) =u (1: Nu);
%y is u delayed Td seconds
ty=0: tiv:(60+Td-tiv);
%time intervals set (60+Td seconds)
%plot input and output
subplot (2,1,1)
plot (tu, u,'k');
%plots input axis ([0 70 -4
4]);
title ('noise signal u')
subplot (2,1,2)
plot (ty, y,'k'); %plots output (has delay) axis
([0 70 -4 4]);
title ('noise signal y, which is delayed u');
xlabel('seconds');
EC23102
DIGITAL SIGNAL PROCESSING

Practical 6
% To generate a triangular signal
clc; clear all; close all;
N = input ('enter the number of
cycles....'); M = input ('enter the
amplitude....'); t1 = 0:0.5:M; t2 = M: -
0.5:0; t = []; for i = 1: N, t = [t, t1,
t2]; end; subplot (211); plot(t); grid on;
xlabel ('---> time');
ylabel ('---> amplitude');
title('analog triangular signal');
subplot (212);
stem(t);
grid on;
xlabel ('---> time');
ylabel ('---> amplitude');
title ('discrete triangular signal');

Result:

enter the number of cycles....3 enter

the amplitude....4
EC23102
DIGITAL SIGNAL PROCESSING

Practical 7
% MATLAB program for linear convolution
clc; clear all; close all;
disp('linear convolution program');
x=input('enter i/p x(n):'); m=length(x);
h=input('enter i/p h(n):'); n=length(h);
x=[x,zeros(1,n)];
subplot (2,2,1), stem(x);
title ('i/p sequence x(n)is:');
xlabel('---->n');
ylabel('---->amplitude');
grid; h=[h,zeros(1,m)]
; subplot (2,2,2), stem(h);
title ('i/p sequence h(n)is:');
xlabel('---->n');
ylabel('---->amplitude');
grid; disp ('convolution of x(n) & h(n) is
y(n):'); y=zeros (1, m+n-1); for i=1:m+n-1
y(i)=0; for j=1:m+n-1 if(j<i+1)
y(i)=y(i)+x(j)*h(i-j+1); end end end y
subplot (2,2, [3,4]), stem(y);
title ('convolution of x(n) & h(n) is
y(n):'); xlabel('---->n'); ylabel('----
>amplitude');
EC23102
DIGITAL SIGNAL PROCESSING

Practical 8

% Program To prove the time shifting property of DFT


clc; clear
all;
close
all;
x = input ('enter the input sequence=')
N = length(x); %data length
W = exp(-j*pi*2/N) X = fft(x);
subplot (1,2,1) stem(x);
xlabel('---------->N');
ylabel('amplitude');
title ('plot of input signal x(n)') k = 0: N-1; %
frequency index m = 2; % number of shift Y= W.^(-
m*k). * X; y= ifft(Y) mag=abs(y) subplot (1,2,2)
stem(mag);
xlabel('---------->N');
ylabel('amplitude');
title ('plot of input shifted signal x(n-m)')

Output:enter the output sequence= 6


EC23102
DIGITAL SIGNAL PROCESSING

Practical 9

% DFT Computation of square pulse without built in function


clc; clear
all;
close
all;
x= [zeros (1,32), ones (1,64), zeros (1,32)]
X=fft(x) X1=fftshift(X) subplot
(2,1,1) plot(x) xlabel('time')
ylabel('amplitude') title
('time domain square pulse')
subplot (2,1,2) plot(abs(X1))
xlabel('frequency')
ylabel('magnitude')
title ('furrier transform of sequence')

Practical 10

% Program To prove the Linearity property


clear all; close
all;
N=input ('enter the value for N=
') x1=input ('enter the x1 input
x1=') x2=input ('enter the x2
input x2=') a=input ('enter the
x2 input a=') b=input ('enter the
x2 input b=') y1=a.*x1+b.*x1
Y1=fft (y1, N)
X1=fft (x1, N)
X2=fft (x2, N)
Y2=a.*X1+b.*X2
MagY1=abs(Y1)
MagY2=abs(Y2)
phaseY1=angle(Y1)
*180/pi
phaseY2=angle(Y2)
*180/pi figure
k=0:1:(N-1) subplot
EC23102
DIGITAL SIGNAL PROCESSING

(2,2,1); stem (k,


MagY1)
xlabel('N-point'); ylabel ('Magnitude of Y1') subplot (2,2,3); stem (k,
MagY2)
xlabel('N-point'); ylabel ('Magnitude of
Y2') subplot (2,2,2); stem (k, phaseY1)
xlabel('N-point'); ylabel ('phase of Y2')
subplot (2,2,4);
stem (k, phaseY2) xlabel('N-point');
ylabel ('phase of Y2') if Y1==Y2
disp ('Linearity property satisfied for the given sequence')
else
disp('Linearity property not satisfied for the given sequence') end

You might also like