Using Matlab to form a Square Wave

JohnCU

Banned
Dec 9, 2000
16,528
4
0
Please do not move this to programming, it is more of a question about Fourier analysis and actually summing the stuff to make a square wave...

I'm supposed to write a matlab program to synthesize a square wave. Here's what I've got so far...

har=input('Enter highest harmonic (positive integer, enter 0 to exit: ');
freq=input('Enter the fundamental frequency in hertz: ');
amp=input('Enter the amplitude: ');
Ts=[linspace(0,1,8192)];
y = 0;
counter = 0;
for ind=1:har
if (rem(ind,2) == 0)
ak = 0;
else
if (rem(counter,2) == 0)
ak = 4 / (pi*ind);
else
ak = -4 / (pi*ind);
end
counter = counter + 3;
end
y = y + ak*cos(2*pi*freq*Ts*ind);
end
plot(Ts,y);

I get a freaky looking signal that is not square at all...aren't I just supposed to go through and add up all the cosines evaluated at the different harmonics? (All that fancy counter stuff in there is to create the ak values, 4/pi, -4/3pi...etc...)