1
$\begingroup$

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

  • 0
    @Ed: yes, but he/she edited his/her text since my comment has been posted.2012-08-27

3 Answers 3

4
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: Cos wave

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

  • 0
    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!2012-08-26
1

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,...)

  • 0
    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.2012-08-26
1

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$:

enter image description here