# Getting the amplitude and phase of harmonics in C

I have a periodic series of 360 values. How can I use the fftw c libraries to get the amplitude and phase of the first, second, third and fourth harmonic?

If I do this for N=360

fftw_plan_r2r_1d(N,input_array,output_array,FFTW_R2HC,FFTW_ESTIMATE);


I can get the 360-point Discrete Fourier Transform (DFT) where output_array is complex Hermitian in half-complex format.

Where k$$^{th}$$ component of output_array is the real part and (N-k)$$^{th}$$ component of output_array is the imaginary part.

So if I want the amplitude or magnitude(??) of the first harmonic should I do this?

ampl_1sth=sqrt(output_array[1]*output_array[1]+output_array[N-1]*output_array[N-1])


Is that correct? then the amplitude of the second harmonic will be the same but with output_array[2] and output_array[N-2] and so on right?

And then how can I get the phase of the first, second, third and fourth harmonic with the info from the DFT?

For a reference to fftw see here www.fftw.org/fftw3.pdf

Thank you.

• Duplicate: stackoverflow.com/questions/17224874/… Jun 21, 2013 at 6:00
• Also not to forget about k=0 and k=n/2 (even) for DC and Nyquist bin Feb 3, 2020 at 14:06

You just need to know how to compute magnitude and phase of a complex number $z=z_R+iz_I$:

$$|z|=\sqrt{z_R^2+z_I^2}\\ \arg\{z\}=\left\{\begin{array}{ll}0,&z_R=z_I=0\\ \pi/2&z_R=0,\; z_I>0\\ -\pi/2&z_R=0,\; z_I<0\\ \arctan\left(\frac{z_I}{z_R}\right),&z_R>0\\ \arctan\left(\frac{z_I}{z_R}\right)+\pi,&z_R<0,\;z_I\ge0\\ \arctan\left(\frac{z_I}{z_R}\right)-\pi,&z_R<0,\;z_I<0\\ \end{array}\right.$$

Luckily, the computation of the phase $\arg\{z\}$ is simplified by the existence of the function atan2 in most programming languages. Watch out, you need to use it like this:

$$\text{phase = }\text{atan2}(z_I,z_R)$$

• Thanks a lot Matt. So if I want the amplitude and phase of the second harmonic I would have to just make those calculations with hc[2] and hc[N-2] right? In my case. Jun 21, 2013 at 15:21
• Yes, that's it. Jun 21, 2013 at 16:36

So if I want to calculate for example the fifth_harmonic (phase + amplitude) for every point in the time domain, I have to write:

fifth_harmonic[k] = ampl_5th * cos((5 * PI * k)/N-1 + phase_5th)


or

fifth_harmonic[k] = ampl_5th * sin((5 * PI * k)/N-1 + phase_5th)


?

where:

K=0,......,N-1 are the sampling point in time domain

fifth_harmonic - amplitude for the fifth harmonic

phase_5th - phase for the fifth harmonic

which one I have to use: the sin or cos?

• Is correct to say that if you expect a real output you have to use the cosin component? Otherwise yo have to use a combination of both cosin and sin component? Nov 25, 2015 at 10:20