# Defining a function that returns “undefined” if its value is outside of a specific range

I want to define a function f(x) which:

• $f(x)=x^3 +10x+ 5$ if $f(x) >0$

• $f(x)=Undefined$ if $f(x) <0$

I have a idea:

f = Function[x, ConditionalExpression[x^3 +10x+ 5, x^3 +10x+ 5 > 0]]


but if $f(x)$ is a complicated and long expression, then the code is very long. Any one have another idea?

-
Do you want the returned value to the symbol Undefined, the string "undefined", or the standard unevaluated expression? Also, I think if $f(x)$ is a long expression, the code will probably have to be at least as long. –  Michael E2 Apr 4 '14 at 10:41

f4[x_] := Block[{val = (x^3 + 10 x - 5)}, val /; val >= 0]


f4 will return unevaluated if the condition is not fulfilled. If it is desirable to get some value returned instead, it is convenient to define it as Indeterminate or Undefined by adding second definition:

f4[_] = Undefined


Now for f[1] you get 6 and for f[0] you get Undefined.

-

There are many ways:

f1[x_?NumericQ] := (x^3 + 10 x - 5) /. n_?Negative -> "undefined"


or more safe:

f2[x_] :=  With[{val = (x^3 + 10 x - 5)}, If[Negative@val, "undefined", val]]


another one for open intervals:

f3[x_] := Clip[(x^3 + 10 x - 5), {0, ∞}] /. (0 -> "undefined")

-
You can use Clips third argument to avoid the replacement and (probably) speed this up somewhat seriously, see e.g. Clip[{0, 1, 2, 3, 4}, {1, 3}, {low, high}] –  Yves Klett Apr 4 '14 at 12:02
@YvesKlett oh of course, what was I thinking about? :) Thanks. –  Kuba Apr 4 '14 at 17:24