MATLAB: To Get Correct FFT Result the length(x) must be An Integral Multiple of 100


Hi, all
I'm trying to get the amplitude- frequency relationship and phase- frenquency relationship using fft. My signal is given by:
t=0:0.005:14; % Time [s] Where mod(length(t),100)~=0
% t=t=0:0.005:14; t(end)=[]; % Where mod(length(t),100)==0
To get the amplitude and the phase of the signal of specified frequency, I used:
The question is, if the length(Vs) is an integral multiple of 100 (100,2700, etc.), the programe returns a correct amplitude and phase like:
Both Amplitude and Phase value at the DC, 20Hz, 40Hz is the setting value. However, once the length(Vs) is not of an integral multiple of 100, the same program returns a totally wrong result like:
I don't know the reason, and I want a method by which I can get right Spectrum no matter what the length(Vs) is.(On the premise of guaranteeing sampling theorem).

Best Answer

The desired plot will be obtained when N, the number of elements of t, is an integer multiple of the ratios Fs/Fn, where Fs is the sample frequency and Fn are the frequencies in Vs (in Hz). In this case we have
Fs = 200;
Fn = [20 60];
Given these vaues, selecting N = k*100 will satisy the criterion:
syms k N
N = k*sym(100);
N*sym(Fn)./sym(Fs) % integer valued for all integer k
ans = 
Here is the "good" case in the question:
N = 2800;
N.*Fn./Fs % integer

ans = 1×2
280 840
tfinal = func(N,Fs,Fn)
tfinal = 13.9950
Here is another case, where N satisfies the criteria, but is not a muliple of 100
N = 2820;
N.*Fn./Fs % integer
ans = 1×2
282 846
tfinal = func(N,Fs,Fn)
tfinal = 14.0950
As you already showed, choosing N = 2801, which does not satisfy the criterion, results in an undesired plot
N = 2801;
N.*Fn./Fs % not both integers
ans = 1×2
280.1000 840.3000
tfinal = func(N,Fs,Fn)
tfinal = 14
Note this result is not wrong. It is correct based on the input parameters.
function tfinal = func(N,Fs,Fn)
t = (0:(N-1))/Fs;
Vs = 10*cos(2*pi*Fn(1)*t-pi/5)+13*cos(2*pi*Fn(2)*t+pi/6);
Spectrum = fft(Vs)/length(Vs);
Spectrum(2:end-1) = Spectrum(2:end-1)*2;
Amplitude = abs(Spectrum);
Phase = angle(Spectrum);
xlim([0 Fs/2])
tfinal = t(end);