7

I realize this question has been asked many times, but I am fairly new at Mathematica and the other answers are very complex, and certainly too complicated for this simple code I am trying to write.

I want to restrict the function below to be between -1 and 1. I do not want to restrict the plot; I want to restrict the function itself.

f[x_] := -(x + c)^2

Is there a simple way I can do this?

Alexey Popkov
  • 61,809
  • 7
  • 149
  • 368
Physika
  • 183
  • 1
  • 7

2 Answers2

12

I think the easiest way is to use Condition which has the operator form /;.

f[x_ /; -1 <= x <= 1, c_] := -(x + c)^2

Then

With[{c = -1/4}, Plot[f[x, c], {x, -2, 2}]]

plot

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
4

Amplifying on m_goldberg's answer: The Condition can include a Message to use when the argument is outside the allowed interval.

ClearAll[f]

f::arg = "Argument value of `1` must be in the closed interval {-1, 1}.";

f[x_, c_] /; If[TrueQ[-1 <= x <= 1], True, Message[f::arg, x]] := -(x + c)^2

Then, an argument outside the interval generates a Message

f[2, c]

enter image description here

The Message can be turned Off

With[{c = -1/4}, Off[f::arg]; Plot[f[x, c], {x, -2, 2}]]

enter image description here

Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198