# Matlab - Constructing a Cosine wave with IFFT

My apology if following question is too simplistic to be asked but I have the following code which generates a nice sine wave for me:

N=64;
X=zeros(N,1);
X(2)=-32j;
X(N)=32j;
x=ifft(X);
stem(real(x)); Now I was thinking I should be able to construct a cosine wave in the similar way by changing the X(2) and X(N) values into some real mirrored values say X(2)=-32 and X(N)=32. However, the output is not what I want i.e. a cosine wave You must keep in mind that for a real-valued signal, second half of your spectrum is a complex conjugate of all values below the Nyquist frequency. In your case:

X(2) = -32
X(N) = 32


as you can see the coefficients are not the complex conjugate of each other. Because of that you are ending up with round-off errors, since two frequency components are cancelling each other out.

Here is some modification to your code:

clc, clear all, close all
fs = 32;
dt = 1/fs;

N=64;
X=zeros(N,1);
X(2)=32;
X(N)=conj(X(2));
s=ifft(X)';

td = linspace(0, (length(s)-1)*dt,     length(s));

stem(td, s, 'b', 'linewidth', 2)
grid on
legend({'reconstructed signal'})


Which gives: • Thanks for the answer. So what you changed in my code was basically changing X(N)=32 into X(N)=conj(32) . What's the mathematical interpretation of this? i.e. conjugate of a real value. – Bababarghi Oct 23 '15 at 12:28
• Complex conjugate – jojek Oct 23 '15 at 12:34
• conj(32) is 32, so X(N)=conj(32) is the same of X(N) = 32, or did I miss something ? The error of OP was just he did X(2) = -32 instead of X(2) = 32. But I like your way to do it, it prevents errors. – MaximGi Feb 26 '16 at 9:11
• If you are asking about the line X(N)=conj(X(2)); then it is there to automatically calculate the coefficient when OP wants to play with the code. Indeed X(N) will be 32 in the example above. – jojek Feb 26 '16 at 9:14