# square wave matlab code

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

-
What are x,w and Vg in your formula? Also, you are not building up an array with that formula, just a number. –  Raskolnikov Aug 26 '12 at 7:46
I guess you need more than just $5$ sinusoidals to get a square wave. Try large n = 100 or n = 500? –  user2468 Aug 26 '12 at 20:11
Is there a specific reason you're using a series representation to generate this square waves? Because there are more direct ways to output a series of 0's and 1's. –  akkkk Aug 26 '12 at 21:37
@Raskolnikov The variable wave is an array, because cos(i*w) returns an array for the array w = 2*pi*(0:0.001:10). –  Arkamis Aug 27 '12 at 16:08
@Ed: yes, but he/she edited his/her text since my comment has been posted. –  Raskolnikov Aug 27 '12 at 17:38

x = 0:0.001:10;
x = x';
n = 5;
wave = zeros(size(x,1),1);
for i = 1:2:n
wave = wave + cos(2*i*pi*x)/(2*i*pi);
end
plot(x,wave)


Two comments for MATLAB etiquette, 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 Vg is, 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 mysterious Vg:

But if you switch the cosine to sine, it would be more like a square wave:

-
Hmm, that's interesting. Seems like the problem was that I was using cosine, instead of sine. Didn't occur to me that it would be so different. Thanks! –  suzu Aug 26 '12 at 23:22

At the end of your code, you come up with just a 1*1 array.
Moving the plot(x,wave) in the for loop and using hold on after that could do a rather sloppy fixing. Try plot(x,wave,'*') since the value of n is too small. Otherwise change n to about 1000.
Also please present the complete code(what are x,w,...)

-
I edited my above post to include the values of x and w. However, i tried the new code with your suggestions and still i can't get it to quite be a square wave even with n = 1000. –  suzu Aug 26 '12 at 20:08

Here is a version of your code that computes the wave-form with a single line of code:

x = 0:0.001:10;
w = 2*pi*x;
n = 5;
Vg = 1;
k = 1:2:n;

W = ((4*Vg/pi)./k)*(sin(kron(k',w)));


As other responders have mentioned, $\sin$ looks to work better.

Here is a plot for $n=1000$:

-