square - Square wave - MATLAB (original) (raw)

Main Content

Syntax

Description

[x](#d126e271132) = square([t](#d126e271063)) 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.

example

[x](#d126e271132) = square([t](#d126e271063),[duty](#d126e271101)) 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.

example

Examples

collapse all

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

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

Plot the square wave and overlay a sine. Normalize the _x_-axis by π. The generated square wave has a value of 1 for intervals [nπ,(n+1)π) with even n and a value of -1 for intervals [nπ,(n+1)π) with odd n. The wave never has a value of 0.

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

Figure contains an axes object. The axes object with xlabel t / blank pi contains 2 objects of type line.

Repeat the calculation, but now evaluate square(2*t) at 121 equally spaced numbers between -π and 2π. 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, -π and 2π.

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

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

Figure contains an axes object. The axes object with xlabel t / blank pi contains 2 objects of type line.

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(2pi30*t,37)+randn(size(t))/10;

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

Figure Duty Cycle Plot contains an axes object. The axes object with xlabel Time (seconds), ylabel Level (Volts) contains 9 objects of type line. One or more of the lines displays its values using only markers These objects represent signal, mid cross, upper boundary, upper state, lower boundary, mid reference, lower state.

Input Arguments

collapse all

Time array, specified as a vector, matrix, or _N_-D array. square operates along the first array dimension oft with size greater than 1.

Data Types: single | double

Duty cycle, specified as a real scalar from 0 to 100.

Data Types: single | double

Output Arguments

collapse all

Square wave, returned as a vector, matrix, or _N_-D array.

Extended Capabilities

Version History

Introduced before R2006a

expand all

The square function supports code generation for graphical processing units (GPUs). You must have MATLAB® Coder™ and GPU Coder™ to generate CUDA® code.