# Math Help - Plotting a square wave using MATLAB

1. ## Plotting a square wave using MATLAB

The following MATLAB code plots a square wave.

Code:
x=linspace(-4*pi,4*pi,1000);

for i=1:125
y(i)=1;
end
for i=125:250
y(i)=-1;
end
for i=250:375
y(i)=1;
end
for i=375:500
y(i)=-1;
end
for i=500:625
y(i)=1;
end
for i=625:750
y(i)=-1;
end
for i=750:875
y(i)=1;
end
for i=875:1000
y(i)=-1;
end

plot(x,y)
axis([-4*pi 4*pi -2 2])
xlabel('x')
ylabel('Square wave')
I have attached the output. I am curious to know why MATLAB plots those vertical lines although I didn't ask it to.

2. ## Re: Plotting a square wave using MATLAB

It's not really a square wave.
It's a number of dots that belong to a square wave.
Furthermore those lines are not vertical.
You have for instance y(124)=1 and y(125)=-1.
Matlab connects all the dots with lines, and these 2 dots are connected with an almost vertical line.