0
$\begingroup$

Can we express functions such as:

$$f(x)=-x \quad -2\leq x \leq 0\\f(x)=x \quad 0< x \leq 2\\f(x+4)=f(x)$$

On Mathematica? I tried something with piecewise functions but it didn't work. Namely, I couldn't make the last condition. I tried:

f[x_] := Piecewise[{{-x, -2 <= x <= 0 }, {x, 0 < x <= 2 }}]
f[x_ + 4] := f[x]
$\endgroup$
3
  • $\begingroup$ Note that in this particular case and due to the form of the piecewise function, you can use the more straightforward f[x_]:=Abs[x] $\endgroup$ Apr 26 at 16:07
  • 2
    $\begingroup$ Try f[x_]:= f[Mod[x,4,-2]] $\endgroup$ Apr 26 at 16:15
  • $\begingroup$ See, for example, mathematica.stackexchange.com/a/57625/7936 and other answers to that question. $\endgroup$
    – evanb
    Apr 26 at 19:36
3
$\begingroup$

Try this:

    f[x_] := Abs[TriangleWave[x/8]];
Plot[f[x], {x, -8, 8}]

with the following effect:

enter image description here

Have fun!

$\endgroup$
2
  • $\begingroup$ I think you need to scale (y) by 2: 2 Abs@TriangleWave[x/8] (+1) $\endgroup$
    – Michael E2
    Apr 26 at 20:33
  • $\begingroup$ @ Michael E2 You are right $\endgroup$ Apr 27 at 8:01
1
$\begingroup$

Using Piecewise

Clear[f]

To avoid an attempt at infinite recursion, the argument of f should be restricted to numeric values.

f[x_?NumericQ] := Piecewise[{
   {-x, -2 <= x <= 0},
   {x, 0 < x <= 2},
   {f[x - 4], x > 2},
   {f[x + 4], x < -2}}]

f /@ {-17.25, -1.5, 1.75, 16.5}

(* {1.25, 1.5, 1.75, 0.5} *)
$\endgroup$
1
$\begingroup$

Another way:

g[t_] := If[Abs[t] < 2, Abs[t], g[t - 4 Sign[t]]]

which produces the same plot as Alexei's answer.

$\endgroup$
1
$\begingroup$

Using the Periodic operator I wrote in this answer

Periodic[T_, offset_ : 0][f_] := f@*((Mod[#, T] - offset) &)

we can say

f = Periodic[4,2][Abs]

to get the function of interest.

$\endgroup$
0
$\begingroup$

Another way:

f = Interpolation[{{-2, 2}, {0, 0}, {2, 2}},
 InterpolationOrder -> 1, PeriodicInterpolation -> True];
Plot[f[x], {x, -4, 6}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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