The problem is caused by round-off errors in phase
, so don't use them when calulating the sine and consine of the phase angles. Instead, use trig identities cos(atan(A))=(1+A^2)^(-1/2)
, and sin(atan(A))=A*(1+A^2)^(-1/2)
, and so
re = mag .* real(F)./sqrt(real(F).^2+imag(F).^2);
im = mag .* imag(F)./sqrt(real(F).^2+imag(F).^2);
EDIT: I think that if you want to change the phase angle by S
, this will do the trick:
re = mag .* (real(F)*cos(S)-imag(F)*sin(S))./sqrt(real(F).^2+imag(F).^2);
im = mag .* (real(F)*sin(S)+imag(F)*cos(S))./sqrt(real(F).^2+imag(F).^2);
EDIT2: You will still sometimes get bad results with non-zero imaginary part (e.g. if S=pi
), and you will need to plot either stem(real(x_i))
or stem(1:length(x_i),x_i)
as Luis suggested.