Need an example
Closed this issue · 4 comments
An example of generating a signal, running fft and retrieve parameters would be welcome.
I try to make a unit test, but I need help to retrieve the expected value.
Would expect to find such help http://fr.mathworks.com/help/matlab/ref/fft.html
// Make 50 Hz signal
final int sampleRate = 44100;
final int signalFrequency = 50;
float[] signal = new float[sampleRate];
for(int s = 0; s < sampleRate; s++) {
double t = s * (1 / (double)sampleRate);
signal[s] = (float)Math.sin(2 * Math.PI * signalFrequency * t);
}
// Execute FFT
FloatFFT_1D floatFFT_1D = new FloatFFT_1D(sampleRate);
floatFFT_1D.realForward(signal);
// Recover expected 50 Hz frequency with value 1
...
thank you
Ok, found it.
// Make 50 Hz signal
final int sampleRate = 44100;
final int signalFrequency = 50;
float[] signal = new float[sampleRate];
for(int s = 0; s < sampleRate; s++) {
double t = s * (1 / (double)sampleRate);
signal[s] = (float)Math.sin(2 * Math.PI * signalFrequency * t);
}
// Execute FFT
FloatFFT_1D floatFFT_1D = new FloatFFT_1D(sampleRate);
floatFFT_1D.realForward(signal);
// Extract Real part
float localMax = Float.MIN_VALUE;
int maxValueFreq = -1;
float[] result = new float[signal.length / 2];
for(int s = 0; s < result.length; s++) {
//result[s] = Math.abs(signal[2*s]);
float re = signal[s * 2];
float im = signal[s * 2 + 1];
result[s] = (float) Math.sqrt(re * re + im * im) / result.length;
if(result[s] > localMax) {
maxValueFreq = s;
}
localMax = Math.max(localMax, result[s]);
}
// 50 Hz signal is graduated to 1
assertEquals(1, localMax, 1e-12);
// Expected 1 value on 50 Hz band
assertEquals(signalFrequency, maxValueFreq);
Some documentation are still welcome. But I close this issue.
Thanks for the example, it helped me a lot.
On a side node, I think that the code above does not deal properly with the fact that results[1]
isn't the imaginary part of the first item, but actually the real part of the item at index n/2
, as explained in the documentation:
a[2*k] = Re[k], 0<=k<n/2
a[2*k+1] = Im[k], 0<k<n/2
a[1] = Re[n/2]
Of course, the code works well because the example signal has just a frequency component at 50Hz, but if you plan to adapt the code above to real world applications, you may need some extra step.
Could you please briefly explain me how does it store values?
a[1]
is real part of the item n/2
but where does it store imaginary part of the first item?
The imaginary part of the first item is always 0, so there is no need to store it.