# Using Piecewise to create a periodic waveform

I want to create a piecewise function that repeats after t=T.

Clear[t, T, s];
T = 5;
s[t_] := \[Piecewise] {
{t, 0 < t <= 1},
{1, 1 < t <= 2},
{-t + 3, 2 < t <= 3},
{0, 3 < t <= T}
}


To make it periodic, I add the following:

s[t_] := s[t - T] /; t > T
Plot[{s[t], Evaluate@D[s[t], t]}, {t, 0, 12}, Exclusions -> None]


It plots alright, but the derivative of s[t] stops at the end of T. Question What is the correct way of defining and plotting the derivative and integral of a periodic waveform defined using the Piecewise function?

• Plot[{s[t], D[s[x], x] /. x -> Mod[t, T]}, {t, 0, 12}]?
– kglr
Jan 2, 2022 at 2:45
• That's three good solutions on one page using Mod. kglr's solution (in the comments) is to find the derivative for the base case and plot it using Mod for different ranges. Nasser's solution is suitable for teaching canonical use of Piecewise. It defines a base function and then defines a periodic function based on it, perhaps using T as a parameter. Ted Ersek's solution shows the Gibb's phenomenon that alludes to MMa's use of Series being used in the background. My thanks to all the respondents.
– Syed
Jan 2, 2022 at 6:39

One way could be

Clear[t, T, s, s0];
T = 5;
s[t_] := Piecewise[{{s0[Mod[t, T]], t > T}, {s0[t], True}}]
s0[t_] := Piecewise[{{t, 0 < t <= 1}, {1, 1 < t <= 2}, {-t + 3,
2 < t <= 3}, {0, 3 < t <= T}}]


and now

Plot[s[t], {t, 0, 12}, Exclusions -> None] and

Plot[Evaluate[D[s[t], t]], {t, 0, 12}, Exclusions -> None] And

Plot[{s[t], Evaluate[D[s[t], t]]}, {t, 0, 12}, Exclusions -> None] • Thanks. Can you please elaborate why my method fails for the derivative but not for the plot?
– Syed
Jan 1, 2022 at 21:14
• @Syed I just noticed that when you had Clear[t,T,s]; T=5; s[t_]:=Piecewise[{{t,0<t<=1},{1,1<t<=2},{-t+3,2<t<=3},{0,3<t<=T}}]; s[t_] := s[t - T] /; t > T then D[s[t],t] gives zero for t>3. But changing it to s[t_]:=Piecewise[{{s0[Mod[t,T]],t>T},{s0[t],True}}]; s0[t_]:=Piecewise[{{t,0<t<=1},{1,1<t<=2},{-t+3,2<t<=3},{0,3<t<=T}}] now D[s[t], t] now gives correct derivatives mod T. Jan 2, 2022 at 4:27
Clear[s];

s[t_?(0<=#<=5&)]:=\[Piecewise]{
{t,0<=t<=1},
{1,1<t<=2},
{-t+3,2<t<=3},
{0,3<t<=5}
};

s[t_?(Element[#,Reals]&)]:=s[Mod[t,5]];


Edit by @Syed (to include plot)

Plot[{s[t], Evaluate[D[s[t], t]]}, {t, 0, 12}, Exclusions -> None] **** Edit **** The derivative plotted above has errors.

Wolfram Tech Support said: Since there are conditions on the input, there is no symbolic derivative, so s'[real number] is computing an approximate derivative, which is of very low quality.

Another solution is given above that works much better.