问题
I have a ascii file containing 2048 x and y value pairs. I just want to know how to plot fft of y in MATLAB. I am writing following MATLAB code but could not be able to find appropriate result.
How can I do this? This is what I have tried:
I = load('data1.asc');
for i = 1:2048
y = I(:,2);
end
plot(x)
Fs = 40000;
T = 1/Fs;
L = 2000;
NFFT = 2^nextpow2(L);
Y = abs(fft(y,NFFT))/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
figure, plot(f,2*abs(Y(1:NFFT/2+1)))
axis([0 40000 0 40])
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
回答1:
Instead of diving straight into MATLAB's FFT routine you should instead consider using the periodogram function. When people say "FFT" they usual mean PSD or periodogram, i.e. a plot of power spectral density using a suitably windowed and FFTed sample. The periodogram function in MATLAB takes care of all the details of this for you, i.e. applying a window function, calculating the FFT, deriving magnitude from FFT output, appropriate scaling of axes, and even plotting if required.
Note: periodogram
is in the MATLAB Signal Processing Toolbox - if you do not have access to this then you can either consider using Octave (free MATLAB clone) which has a periodogram
clone, otherwise you would need to put the various building blocks together yourself:
- window function
- FFT
- calculate magnitude
- take scare of scaling of freq and magnitude values
- plot PSD
回答2:
The fft
part of the code looks good to me. However, this bit doesn't make much sense:
for i = 1:2048
y = I(:,2);
end
What are you trying to do here? You're not using the loop index i
at all in the for loop.
Also, I assume y
is of length 2000, can you confirm? Otherwise L = 2000
should be changed to L = length(y)
. Similarly, I assume that the sampling frequency of the data is 40kHz, otherwise Fs = 40000
is not correct.
EDIT following discussion in comments:
With the data that you have provided, I get the same results. The only thing I did is exclude the last data point from the analysis when it drops to zero. The way you read the data still doesn't make sense to me. Note I am using Octave, not MATLAB, but the code should give the same results in MATLAB.
load('ascii_value.txt')
y = ascii_value(1:end-1,2);
plot(y)
L=length(y);
Fs = 40000;
T = 1/Fs;
NFFT = 2^nextpow2(L);
Y = abs(fft(y,NFFT))/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
figure, plot(f,2*abs(Y(1:NFFT/2+1)))
axis([0 40000 0 40])
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
The signal looks like this:
and the FFT like this:
Note: if you are sampling at 40 kHz, your FFT can only go up to 20kHz (Nyquist frequency).
来源:https://stackoverflow.com/questions/17828788/how-to-plot-fft-of-ascii-values-in-matlab