Search code examples
matlabplotfftspectral-density

Plotting FFT fails due to vectors not having the same length


I have a csv data of time(1st column) and current amplitude(2nd column). I want to plot FFT of the current. This is actually simulation data over 30ns and data step was 1ps. I can plot the current vs Time in MATLAB. But while doing FFT function, It is not plotting at all as it says

Error using plot
Vectors must be the same length.

Error in FFT_Ideal_current_maxstep_1ps (line 25).
plot(f,Y)

Can anyone help me? I have attached the MATLAB code and the CSV file as well.

I also want to plot the power spectral density. It would be nice if anyone can help. I want to get the FFT and psd over 2GHz or more frequency spectrum range

MATLAB code1:

% open data file
fid = fopen('current_maxstep_1ps.csv');

% Read data in from csv file
readData = textscan(fid,'%f %f','Headerlines',1,'Delimiter',',');

% Extract data from readData
t = readData{1,1}(:,1);
x = readData{1,2}(:,1);

N = length(x);
ts = 0.000000000001;
Fs = 1/ts;
tmax = (N-1)*ts;
tm = 0:ts:tmax;
f = 0:Fs/(N-1):Fs/2;
y = fftshift(fft(x));
Y = abs(y);
plot(f,Y)

Also there is another MATLAB code I tried which plots (here is the picture: FFT picture of code 2) but showing in time domain and I want frequency spectrum like spikes of apmlitudes along the frequency spectrum.

MATLAB Code2:

% open data file
fid = fopen('Ideal_current_maxstep_1ps.csv');

% Read data in from csv file
readData = textscan(fid,'%f %f','Headerlines',1,'Delimiter',',');

% Extract data from readData
xData = readData{1,1}(:,1);
yData = readData{1,2}(:,1);

Ts = 1e-12;
Fs = 1/Ts;
%Fs = 1000;
%Ts = 1/Fs;

X = fft(yData);
plot(xData, abs(X))

Solution

  • The problem is that the length of f and Y are not the same. You can check it using length(f) and length(Y). The reason is that fft also calculates the negative frequencies. Therefore, you should define f as follows:

    f = -Fs/2:Fs/(N-1):Fs/2;
    

    Note that the fft is conjugate symmetric, because the input data is real.

    You can limit the plotted frequency range using the xlim command as follows:

    xlim([0 3*10^9]) % limit x range between 0Hz and 3GHz
    

    enter image description here