# repeating a special type of square wave over time [duplicate]

This question already has an answer here:

How to plot periodic function’s graphic?

How to add periodicity to condition?

I want to repeat the square wave shown in the picture over time after t=0.4 s, so the time period will be 0.4 s. And I want to repeat the same pattern over certain period of time, say 100 s. Anyone can help me with that?

=================

=================

3

=================

You can easily use SquareWave for this:

With[{period = .4},
Plot[SquareWave[x/period] SquareWave[{0, 1}, 2 x/period], {x, 0, 3},
Exclusions -> None, PlotRange -> {-1.1, 1.1}]
]

Thank you so much.
– Ahmed Mamdouh
May 12 ’15 at 19:48

If you try to extend it over 10 seconds you will find a very weird shape at t=5.5 sec. Do you have any idea why’s that?!
– Ahmed Mamdouh
May 12 ’15 at 21:33

Yes, that’s a common issue: the quick variations are overlooked by Mathematica – so you simply have to tell it to be more careful by adding the Plot option PlotPoints -> 300 or some similarly large number.
– Jens
May 12 ’15 at 22:53

Here is my thinking.

You need a periodic function of some kind to generate your periodicity. I decided to use the integer modulo function Mod, combined with a Piecewise function definition.
Since you have four function values, i.e. (1,0,−1,0)(1,0,−1,0)(1,0,-1,0), I used modulo 444 division, which returns any one of (0,1,2,3)(0,1,2,3)(0,1,2,3) for integer input.
Since Mod wants integer input, I take the IntegerPart of the function argument.
Finally, you want each period to be 0.1 units long: that’s the origin of the 10 x10\ x as the argument to Mod.

In short, here are the function definition and its plot:

periodicwave[x_] := Piecewise[{
{1, Mod[IntegerPart[10 x], 4] == 0},
{0, Mod[IntegerPart[10 x], 4] == 1},
{-1, Mod[IntegerPart[10 x], 4] == 2},
{0, Mod[IntegerPart[10 x], 4] == 3}
}
]

Plot[
periodicwave[x],
{x, 0, 1},
ExclusionsStyle -> Automatic
]

If you try to extend it over 10 seconds you will find a very weird shape at t=5.5 sec. Do you have any idea why’s that?!
– Ahmed Mamdouh
May 12 ’15 at 21:39

1

@AhmedMamdouh It is an artifact due to undersampling, i.e. to the number of points that the Plot function uses to construct the graph is too low to capture all the details of the function being plotted. You can force Plot to use more points by adding the option PlotPoints -> 100 inside the Plot function: the weird shape will disappear. If you look at @kguler ‘s answer, PlotPoints is used there as well, presumably for the same reason.
– MarcoB
May 12 ’15 at 22:04

Oh yeah, now it disappeared, thanks.
– Ahmed Mamdouh
May 12 ’15 at 22:33

f = ListInterpolation[{1, 0, -1, 0, 1}, InterpolationOrder -> 0,
PeriodicInterpolation -> True][10 #] &;
Row[Plot[f@x, {x, 0, #}, Frame -> True, PlotStyle -> Thick, Axes -> False,
ImageSize -> 350, PlotPoints -> 200] & /@ {1, 5, 10}]

Ah, Clever… +1
– ciao
May 12 ’15 at 3:07