1
$\begingroup$

I want to plot a piece-wise function like this:

f[x]=1 when -1<=x<=1, and f[x]=0 when x>1 or x<-1

$\endgroup$
2
  • 2
    $\begingroup$ Can you please show what you have tried so far? Have you already looked at Piecewise and Plot? $\endgroup$
    – Szabolcs
    Jul 13, 2021 at 6:32
  • 1
    $\begingroup$ You can use UnitBox[x/2] $\endgroup$
    – demm
    Jul 13, 2021 at 6:40

1 Answer 1

2
$\begingroup$

Big advantage of Mathematica is that you can almost literally write your thoughts

f[x_ /; -1 <= x <= 1] := 1
f[x_ /; x > 1] := 0
f[x_ /; x < -1] := 0

After defining your function, you can plot or do whatever with it

Plot[f[x], {x, -3, 3}]

You can also

  • combine the conditions, for instance f[x_ /; x < -1||x > 1] := 0
  • use Piecewise
  • use UnitBox[x/2]
  • use Boole
  • use If
  • a combination of UnitStep
  • a combination of HeavisideTheta

Each has own advantages, and they differ slightly in treating the discontinuity.

$\endgroup$
1

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.