2
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Michael E2 Apr 4 '14 at 10:41
4
$\begingroup$

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.

$\endgroup$
3
$\begingroup$

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")
$\endgroup$
  • 1
    $\begingroup$ 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}] $\endgroup$ – Yves Klett Apr 4 '14 at 12:02
  • $\begingroup$ @YvesKlett oh of course, what was I thinking about? :) Thanks. $\endgroup$ – Kuba Apr 4 '14 at 17:24

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.