I'm trying to define (and plot) a piecewise function with the following structure:

$$f(x) = \begin{cases} g(x) & nT \leq x \leq \frac{2n+1}{2}T\\ -g(x) & \frac{2n+1}{2}T \leq x \leq (n+1)T \end{cases}$$

where n is an integer, n >= 0 and T is a constant.

The idea is that it cycles between positive and negative after a full period is complete.

My attempt was:

f[x_] := Piecewise[{
     {g[x], (n T <= x <= ((2 n + 1)/2) T) && Element[n, Integers] && (n >= 0)},
     {-g[x], (((2 n + 1)/2) T <= x <= (n + 1) T) && Element[n, Integers] && (n >= 0)}}]

But when I try a test value for x in f[x] it shows n in the conditions for the output, so it seems to not get past the conditions. I believe plotting fails for this reason too.

I have never tried to use Integers in Mathematica.

  • $\begingroup$ Have you specified a value for T ? $\endgroup$
    – Sektor
    Jul 15, 2015 at 15:23
  • $\begingroup$ Sektor: T is specified. Patrick Stevens: Okay, thank you. Using Floor[x/T] instead of n worked. f[x_] := Piecewise[{{g[x], Floor[x/T] T <= x <= ((2 Floor[x/T] + 1)/2) T}, {-g[x], ((2 Floor[x/T] + 1)/2) T <= x <= (Floor[x/T] + 1) T}}] I'm not exactly sure how I would simplify the second condition. belisarius: Thank you, I can see that your version works. $\endgroup$
    – Canada709
    Jul 15, 2015 at 15:51
  • $\begingroup$ It won't let me accept an answer either, I think because I was not properly signed in originally when I posted the question. Apparently I can comment now though $\endgroup$
    – Canada709
    Jul 15, 2015 at 15:53

2 Answers 2


Your problem is that you haven't told Piecewise that n can be arbitrary, so Mathematica thinks it's constant. You'd be better off defining n as Floor[x/T] for the first comparison, rather than asking Mathematica to find an n such that the definition holds (or prove that n doesn't exist).

It looks like you could simplify the second condition to True, by the way: Piecewise checks the pieces in order, so there's no need to give a complicated final condition.


A way following your line of thought:

T = Pi;
g[x_] := Sin@x
f[x_?NumericQ] := Piecewise[
     {{g[x] , Quiet@Resolve@Exists[n, n ∈ Integers && (n + 1/2)T <= x <= (n + 1)T]}},
Plot[f[x], {x, 0, 10}]

Mathematica graphics

I would do it this way instead:

Plot[-g[x] SquareWave[x/T], {x, 0, 10}]

Mathematica graphics

And from there you can get an equivalent Piecewise form:

PiecewiseExpand[-g[x] SquareWave[x/T]]

$$\begin{cases} -g(x) & 0\leq (\frac{x}{T} \bmod 1)<\frac{1}{2} \\ g(x) & \text{True} \end{cases}$$


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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