MATLAB: How to perform Fourier Synthesis with cosine waves

fourier synthesis

Hello everyone. I found a lot of ways to achieve Fourier synthesis in MATLAB but they all use sine. I thought the plot of sine and cosine waves we're almost the same but the waveform formed differ drastically. The waveform of the former (sine) almost looks like a square wave but the latter (cosine) didn't even look like it. Is there any possible way to do this using cosine?
Sample code(by user: Youssef Khmou) that I found:
Fs=150;
t=0:1/Fs:4-1/Fs;
f=2;
x=square(2*pi*f*t);
figure;
plot(t,x);
axis([0 1 -2 2]);
% Approximation with Fourier decomposition
y=0;
N=11;
for r=1:2:N
y=y+sin(2*pi*f*t*r)/r;
end
hold on;
plot(t,y,'r');
xlabel('t');
ylabel('magnitude');
hold off;

Best Answer

Hi Julius
Every fourier series is potentially a sum of both sines and cosines. It so happens that the much-overused square wave example looks like a sine wave. It is representable as a sum of sine waves that are odd multiples of the fundamental, 2 Hz in this case. Sines of even multiples, and all the cosines, are not needed in this case.
The code you have is incorrect in the amplitudes of those components. It is missing a factor, and should be
y=y+(4/pi)*sin(2*pi*f*t*r)/r;
You will see that the agreement is much better.
Shifting the square wave to the left by one quarter of a cycle it makes it look like a cosine wave. It is expanded in cosines, with an extra factor of +-1 in the amplitudes:
Fs=150;
t=0:1/Fs:4-1/Fs;
f=2;
T = 1/f; % period
x=square(2*pi*f*(t+T/4)); % cosine-looking square wave
figure(2);
plot(t,x);
axis([0 1 -2 2]);
% Approximation with Fourier decomposition
y=0;
N=11;
for r=1:2:N
extrafactor = (-1)^((r-1)/2);
y=y+(4/pi)*extrafactor*cos(2*pi*f*t*r)/r;
end
hold on;
plot(t,y,'r');
xlabel('t');
ylabel('magnitude');
hold off;
By looking around on the internet and youtube you will be able to find waveforms that use both sines and cosines. If you get interested in this and see what is going on with sines and cosines, then switching over to exp(+-2*pi*i*f*t) complex functions has a lot of advantages.
Related Question