3
$\begingroup$

I am defining a function $f(x)$ and I would like to put undefined values to some $x$. The point is that if I plot the function I don't want an error to be returned, I want that for all the plotting function I will use, it will "ignore" the $x$ corresponding to forbidden values.

Is there a simple way to do this (i.e not writing 50 lines of functions). Is there a simple keyword for that ?

$\endgroup$
1
  • 2
    $\begingroup$ Exclusions perhaps? $\endgroup$
    – Natas
    Commented Sep 30, 2020 at 13:58

2 Answers 2

1
$\begingroup$

I thought that Plot ignored values that are not numbers and also suppressed errors. When I try the following:

f[x_?(2 <= # <= 4 &)] := 1/0;
f[x_?(4 < # <= 6 &)] := Indeterminate;
f[x_] := x^2;

and then

Plot[f[x],{x,0,10}]

I don't get any errors and the plot ignores x values from 2 to 6.

$\endgroup$
1
  • $\begingroup$ Very simple and it works. Thanks. I had examples in which for instance division by zero returned me error in some plots. But I didn't know this keyword indeterminate which looks very usefull. $\endgroup$
    – StarBucK
    Commented Oct 7, 2020 at 13:45
5
$\begingroup$

There are two issues here:

Defining the function

You could use a Condition to prevent the function from evaluating at the forbidden points:

forbiddenValues = {1, E, Pi};
forbiddenQ[x_] := Or @@ Table[x == value, {value, forbiddenValues}] // Evaluate;
f[x_] /; !forbiddenQ[x] := x^2
f /@ {1, 2, E, 4, Pi}
(* {f[1], 4, f[E], 16, f[Pi]} *)

Plotting

From @Natas's comment, use Exclusions:

Plot[f[x], {x, 0, 5}
  , Exclusions -> forbiddenValues
  , ExclusionsStyle -> {None, Directive[Red, PointSize[Large]]}
]

Plot with exclusions

Despite the definition above, you still need to explicitly specify the locations of the exclusions because they do not get detected automatically. Therefore, if the only goal is to generate a plot with the exclusions, I would not bother with defining the function above. Just plot x^2 and use the appropriate exclusion options.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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