I'm having some trouble generating a square wave in matlab via my equation. Just wondering if anyone has some insight on what I am missing here in my code? I was thinking I could easily generate a square wave with just a few harmonics but it doesn't seem to be the case.
Thanks
x = 0:0.001:10;
w = 2*pi*x;
n = 5;
wave = 0;
for i = 1:2:n
wave = wave + ((4*Vg)/(i*pi))*cos(i*w);
end
plot(x,wave)
thanks

Two comments for
MATLABetiquette, it is better handling vector using column, since it is a lot faster, and pre-allocating a variable before entering the loop would make the program more readable and faster.I don't know what your
Vgis, but above code snippet should work, basically what it does is approximating a square wave $W$ by: $$ W = \frac{1}{2\pi}\cos(2\pi x) + \frac{1}{6\pi}\cos(6\pi x) + \frac{1}{10\pi}\cos(10\pi x) $$ The result doesn't look very nice because of your mysteriousVg:But if you switch the cosine to sine, it would be more like a square wave: