# why is the plot of the PSD of this autocorrelation function oscillating?

I was doing an exercise trying to compute the PSD of the following discrete autocorrelation function:

$$r_x(m) =(1/2)^{|m|}$$

In this simple matlab code that I came up with to compute the PSD, I'm getting something that I don't quite understand, why is my frequency response oscillating?.If I plot the abs(Sx) i get a smooth plot but , the dft of a real and even sequence should be real and even as well in my understanding . Why I'm not getting a real frequency response and instead this oscillating response appears? Also, matlab is ignoring the imaginary part of the PSD computed as it says in the command window. What is going on here?

N=100;
m=-N:1:N;
x=(0.5).^abs(m);
subplot(2,1,1)
stem(m,x)
Nfft=512;
Sx=fft(x,Nfft);
subplot(2,1,2)
plot((0:1:Nfft-1)/Nfft,Sx);

Here are the figures:

You are right that the DFT of a real and even sequence is real and even. The problem is that your sequence is not even, at least not the way you programmed it. The fft command doesn't know how you defined the index m. By definition, the first data element in the vector x is associated with the index $n=0$:

$$X[k]=\sum_{n=0}^{N-1}x[n]e^{-j2\pi nk/N}$$

(where $N$ is the DFT length).

Your definition of the sequence x results in a complex spectrum, and the plot command plots the real part of it.

There are two solutions, one of which you already found: either you take the absolute value of the spectrum, or you define the data in such a way that they are indeed even. Due to the implicit periodicity of the DFT, this means that you append the left half of your data (for negative time indicies) at the end of your data vector. Note that the zero padding must now be done in the middle of your data vector:

x = [x(101:201),zeros(1,Nfft-2*N-1),x(1:100)];
Sx = fft(x,Nfft);
max(abs(imag(Sx))            % 2.4980e-16

The resulting spectrum has a small imaginary part due to numerical inaccuracies, so you always need to use real(fft(x,Nfft)), but it's always good to check if the imaginary part is really as small as it should be (around $10^{-16}$ for double precision floating point format, as used in Matlab).