Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to use phase-shifted SquareWave[] functions to create a rectangle wave:

SquareWave[{0, 1}, x/100] * SquareWave[{0, 1}, x/100 - offsetx]

Two things:

  1. This only allows for duty cycles less than 50 %.
  2. While it's handy (it's always the phase shift $0\dots 1$, regardless of horizontal scale), I'm confused that offsetx isn't a function of the x scaling

Is there a general function to create rectangle waves with duty cycles from 0 % to 100 %?

share|improve this question
(FWIW, I think this is more of a math question than a Mathematica question.) – J. M. Jul 1 '12 at 15:05
One elegant solution for duty cycle under 50% would be to multiply two phase-shifted square waves together. I cannot think of an easy analogue for duty cycles in excess of 50%. – Alex Hirzel Jul 1 '12 at 20:25
up vote 10 down vote accepted

See if this helps

squareWave[t_, period_, duty_] := UnitBox[Mod[t/period, 1.]/(2. duty)]

Plot[squareWave[t, 10, 0.8], {t, -2, 21}]

Mathematica graphics

share|improve this answer
As a tiny note, Mod[x, 1] == SawtoothWave[x]. :) That allows us to write squareWave[t_, period_, duty_] := UnitBox[SawtoothWave[{0, .5}, t/period]/duty] – J. M. Jul 1 '12 at 14:20
Niiiice :). Put it in yours – Rojo Jul 1 '12 at 14:30

What I'd do:

With[{d = 1/3}, (* duty cycle *)
 Plot[(1 + (-1)^Floor[x] (-1)^Floor[d - x])/2, {x, -5, 5}, 
  Axes -> {False, True}, Frame -> True, PlotPoints -> 105, 
  PlotRange -> {-5/4, 5/4}]]

square wave with duty cycle 1/3

If you absolutely must use the SquareWave[] function, there is the identity

$$\text{SquareWave}[\{a,b\},x]=\frac{a+b}{2}+\frac{b-a}{2}(-1)^{\lfloor 2 x\rfloor}$$

I'll leave the conversion up to you.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.