In response to a code snippet request, this code is a very simple version of a Frequency Estimator using the FFT method in matlab. Only single tones can be estimated with this code, and the resolution is dependent upon the sampling rate and the length of the fft.
Simply copy the code into an .m file and run with matlab.
%For a real-valued, single tone sine or cosine wave, estimate the frequency %using an fft. Resolution will be limited by the sampling rate of the tone %and the number of points in the fft. %Procedure: %1. Generate the test tone with a given Fs and N %2. Take the fft and keep the first half %3. Detect the maximum peak and its index %4. Equate this index to a frequency %Error Estimate: % (Fs/N)= Hz/bin %Things to keep in mind: %Adding noise to the input will skew the results %windowing will help with the fft %% Clear and close everything clc; close all; clear all; %remove this line if you are trying to use breakpoints %% Just copy into m file, save and run Fs = 1e6; %1MHz fi = 1.333e3; %1kHz t = 0:1/Fs:.5; y = sin(2*pi*fi*t); %Plot the time and frequency domain. Be sure to zoom in to see the waveform %and spectrum figure; subplot(2,1,1); temp = (2/fi)*Fs; plot(y); xlabel('time (s)'); subplot(2,1,2); sX=fft(y); N=length(sX); sXM = abs(sX(1:floor(end/2))).^2; %take the magnitude and only keep 0:Fs/2 plot(0:Fs/N:(Fs/2)-1,sXM); xlabel('Frequency') ylabel('Magnitude') [vv, ii]=max(sXM); %find the index of the largest value in the spectrum freqEst = (ii-1)*Fs/N; %units are Hz resMin = Fs/N; %units are Hz display(freqEst);%display to the command window the results display(resMin);