x = square(t)
generates a square wave with period 2π for the elements of the
time array t. square is similar to the sine
function but creates a square wave with values of –1 and 1.

x = square(t,duty)
generates a square wave with specified duty cycle duty. The
duty cycle is the percent of the signal period in which the
square wave is positive.

Create a vector of 100 equally spaced numbers from $$0$$ to $$3\pi $$. Generate a square wave with a period of $$2\pi $$.

t = linspace(0,3*pi)';
x = square(t);

Plot the square wave and overlay a sine. Normalize the x-axis by $$\pi $$. The generated square wave has a value of $$1$$ for intervals [$\mathit{n}\pi ,\left(\mathit{n}+1\right)\pi $) with even $\mathit{n}$ and a value of $$-1$$ for intervals [$\mathit{n}\pi ,\left(\mathit{n}+1\right)\pi $) with odd $\mathit{n}$. The wave never has a value of $$0$$.

plot(t/pi,x,'.-',t/pi,sin(t))
xlabel('t / \pi')
grid on

Repeat the calculation, but now evaluate square(2*t) at 121 equally spaced numbers between $$-\pi $$ and $$2\pi $$. Change the amplitude to $$1.15$$. Plot the wave and overlay a sine with the same parameters. This new wave is negative at $$t=0$$ and positive at the endpoints, $$-\pi $$ and $$2\pi $$.

t = linspace(-pi,2*pi,121);
x = 1.15*square(2*t);
plot(t/pi,x,'.-',t/pi,1.15*sin(2*t))
xlabel('t / \pi')
grid on

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.