%This relates to Problem 3.3a in Kamen & Heck
%Add up harmonics to generate a square wave.
%Set the value of nh below to see the effect.
%Notice that no matter how many harmonics are summed, there is overshoot
%at the edges. This is the Gibbs phenomenon.

nh=3; %Change this to set the number of harmonics
a0=1;
k=1:nh;
per=3;
w0=2*pi/per;

j=0;
for t=-9:.001:9;
j=j+1;
x(j)=a0;
for k=1:nh;
ak=(3/pi/k)*sin(4*pi*k/3);
bk=(6/pi/k)*(sin(2*pi*k/3))^2;
x(j)=x(j)+ak*cos(k*w0*t)+bk*sin(k*w0*t);
end
end
plot(-9:.001:9,x)