Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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 at 10:41

2 Answers 2

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
1  
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 at 12:02
    
@YvesKlett oh of course, what was I thinking about? :) Thanks. –  Kuba Apr 4 at 17:24

Your Answer

 
discard

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.