Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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

In addition to Kuba's answer:

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.

share|improve this answer

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")
share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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