Matelab 2
Matelab 2
Matelab 2
THE GUIDANCE OF
DR. MADHUSUDHAN MISRA
(Associate Professor)
NORTH EASTERN REGIONAL INSTITUTE OF SCIENCE AND
TECHNOLOGY
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
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);
OUTPUT
EC23102
DIGITAL SIGNAL PROCESSING
CODE
% Generate x values from 0 to
2*pix= linspace(0,2*pi,100);
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
CODE
% Create a 3D plot of a sphere
figure;
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;
patterncheckerboardMatrix=reshape(1:matrixSize^2,matrixSize, matrixSize);
);
OUTPUT
EC23102
DIGITAL SIGNAL PROCESSING
CODE
%Prompt the user for input
num=input ('Enter a non-negative integer r to calculate its factorial:');
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
subplot(1, 2,
2); imshow (gray Image);
title ('Grayscale Image');
%ApplyGaussianblurtothegrayscaleimage
blurredImage=imfilter(grayImage,gaussianKernel,'conv','replicate');
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;
%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);
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');
CODE
%Readanexampleimage
originalImage=imread('cameraman.tif'); %Replacewiththeactualimagefile
%Blurtheimagewiththedefinedkernel
blurredImage=imfilter(originalImage, blurKernel,'conv','circular');
%Addsomenoisetotheblurredimage
noisyBlurredImage=imnoise(blurredImage,'gaussian',0,0.01);
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));
reductionfilteredSignal=wiener2(signalWithNoise,[5,5])
;
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;
image)imageData= imread('cameraman.tif');
%Applythecustomfilterusingconvolution
filteredImage=conv2(double(imageData),edgeFilter,'same');
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')
;
%Adjustthelayout
sgtitle('ImageandFrequencySpectraVisualization');
Q15.MATLABcodetoImplementamethodtovisualize theoriginal image,thecustomfilter, andthe
resultofthefilteringprocess.
%Applythecustomfilterusingconvolution
filteredImage=conv2(double(imageData),edgeFilter,'same');
sgtitle('OriginalImage,CustomFilter,andFilteredImageVisualization');
%Applythecustomfilterusingconvolution
filteredImage=conv2(double(imageData),edgeFilter,'same');
% Display colorbarh
= colorbar;
set(h,'Position',[0.920.10.020.8]);
% Display colorbarh
= colorbar;
set(h,'Position',[0.920.10.020.8]);
%Adjustthelayout
sgtitle('Image,CustomFilter,FilteredImage,andHistograms Visualization');
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));
%Fitthenon-linearmodeltothedata mdl=fitnlm(x,y,modelFun,initialGuess);
legend('Location','Best'); grid
on;holdoff
;
.
Q18.MATLABcodeSaveandloadvariables intheMATLABworkspace.
CODE
x = linspace (0, 10,
100); y =sin(x);
save('workspace.mat','x','y');
%Loadvariablesfromsavedworkspaceload('wo
rkspace.mat');
disp('LoadedVariables:');
disp(['x:'num2str(x(1))'to'num2str(x(end))]);
disp(['y:'num2str(y(1))'to'num2str(y(end))]);
Q20.MATLABcodePerformPCAonadataset.
3Dcoeff =pca(data);
CODE
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);
CODE
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
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');
%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
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
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.
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.
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.
%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.
%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]);
Q38.MATLABcodeDesignandapply a low-passFIRfilter.
%Generateanoisysignal fs
= 1000; % Sampling
frequencyt =0:1/fs:2;
signal=sin(2*pi*50*t)+0.5*randn(size(t));
symsx;
%CalculatetheTaylorseriesexpansion
taylorSeries=taylor(f,'Order',5,'ExpansionPoint',a);
%Displaytheresult disp('Taylor
Series
Expansion:');disp(taylorSeries);
symsts;
% Define a function
f=heaviside
(t);
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;
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:
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
Practical 9
Practical 10