square wave matlab code

28.8k Views Asked by At

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

3

There are 3 best solutions below

1
On BEST ANSWER
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

1
On

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
On

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