x = square(t)
x = square(t,duty)


x = square(t) generates a square wave with period 2π for the elements of time vector t. square(t) is similar to sin(t), but creates a square wave with peaks of ±1 instead of a sine wave.

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


collapse all

Generate Square Waves

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$ at even multiples of $\pi$ and a value of $-1$ at odd multiples of $\pi$. It is never $0$.

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.

t = linspace(-pi,2*pi,121);
x = 1.15*square(2*t);

xlabel('t / \pi')
grid on

Duty Cycle of Square Wave

Generate a 30 Hz square wave sampled at 1 kHz for 70 ms. Specify a duty cycle of 37%. Add white Gaussian noise with a variance of 1/100.

t = 0:1/1e3:0.07;
y = square(2*pi*30*t,37)+randn(size(t))/10;

Compute the duty cycle of the wave. Plot the waveform and annotate the duty cycle.

ans =


Introduced before R2006a

Was this topic helpful?