MATLAB: Plotting results of DFT loop

fftloopplot

I am trying to make multiple DFT from the code of single DFT. But cant figure out how to change plot inputs to see results as it was for single DFT.
%% Plotting single graph of DFT
va= DifVD(1:end); %DifDr(ss(1):ss(2),1);%
y = va; %the signal you want to fft
L = length(y);
Fs=10;
NFFT = 2^nextpow2(L); % Next power of 2 from length of y

Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum.

fg=figure('Renderer', 'painters', 'Position', [100 100 700 500]);
plot(f,2*abs(Y(1:NFFT/2+1))) % semilogx(f,2*abs(Y(1:NFFT/2+1)))%
%% Plotting multiple graphs of DFT
ss=300000:6000:525158;
k=length(ss);
for i=1:k
va(:,i)= DifDr(ss(i):ss(i+1),1);
y = va;
L = length(y(1));
Fs=10;
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y(:,i) = fft(y(:,i),NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum.
fg=figure('Renderer', 'painters', 'Position', [100 100 700 500]);
plot(f,2*abs(Y(1:NFFT/2+1,i)))
end
How should i change last line to plot multiple results?

Best Answer

Hi, it is difficult to provide an exact solution without your original data. However, when I executed your code using random data, at last iteration it is trying to access beyond the last element. After modifying the loop parameter, the code should work.
clc;
clear all;
DifDr=randi(100,525158,5); % Demo data
ss=300000:6000:525158;
k=length(ss);
for i=1:k-1
va(:,i)= DifDr(ss(i):ss(i+1),1); %
y = va;
[L , ~]= size(y);
Fs=10;
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
f = Fs/2*linspace(0,1,NFFT/2+1);
Y(:,i) = fft(y(:,i),NFFT)/L;
% Plot single-sided amplitude spectrum.
fg=figure('Renderer', 'painters', 'Position', [100 100 700 500]);
plot(f,2*abs(Y(1:NFFT/2+1,i))); % semilogx(f,2*abs(Y(1:NFFT/2+1)))%
end