Here is a code-snippet to help you understand how to get the frequency-spectrum using fft in matlab
.
Things to remember are:
You need to decide on a sampling frequency, which should be high enough, as per the Nyquist Criterion (You need the number of samples, at least more than twice the highest frequency or else we will have aliasing). That means, fs in this example cannot be below 2 * 110
. Better to have it even higher to see a have a better appearance of the signal.
For a real signal, what you want is the power-spectrum obtained as the square of the absolute of the output of the fft() function. The imaginary part, which contains the phase should contain nothing but noise. (I didn't plot the phase here, but you can do this to check for yourself.)
- Finally, we need to use
fftshift
to shift the signal such that we get the mirrored spectrum around the zero-frequency.
- The peaks would be at the correct frequencies. Now considering only the positive frequencies, as you can see, we have the largest peak at 100Hz and two further lobs around
100Hz +- 10Hz
i.e. 90Hz and 110Hz.
Apparently, 110Hz is the highest frequency, in your example.
The code:
fs = 500; % sampling frequency - Should be high enough! Remember Nyquist!
t=[-.2:1/fs:.2];
s= 5.*(1+cos(2*pi*10*t)).*cos(2*pi*100*t);
figure, subplot(311), plot(t,s);
n = length(s);
y=fft(s);
f = (0:n-1)*(fs/n); % frequency range
power = abs(y).^2/n;
subplot(312), plot(f, power);
Y = fftshift(y);
fshift = (-n/2:n/2-1)*(fs/n); % zero-centered frequency range
powershift = abs(Y).^2/n;
subplot(313), plot(fshift, powershift);
The output plots:
- The first plot is the signal in the time domain
- The signal in the frequency domain
- The shifted fft signal
plot(t, abs(y))
? also, your time vector is too short to see the effect of the smaller frequency. Try for examplet=[-0.02:10^-3:0.2];
– Luis Mendot
is not really the axis you want to be plottingy
against. – Mad Physicistt=[-0.2:10^-3:0.2];
? Right? Because witht=[-0.02:10^-3:0.2];
, we have shifted the whole plot. – Duck Dodgers