Is it possible to plot a function over a interval with a gap in the middle; e.g., $f(x)=x^2$ over $-5<x<-1\cup1<x<5$?
I am using Mathematica 7 and most of the options in the answers don't seem to work for me.
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityIn V8 and up, one can use ConditionalExpression
:
Plot[ConditionalExpression[x^2, -5 < x < -1 || 1 < x < 5], {x, -5, 5}]
Response to updated question
This might work in all versions of Mathematica:
Show[
Plot[x^2, {x, -5, -1}],
Plot[x^2, {x, 1, 5}],
PlotRange -> All]
Piecewise[]
with Indeterminate
as the default case works here as well.
$\endgroup$
Dec 9, 2016 at 21:11
You can also define f conditionally:
f[x_] := x^2 /; (-5 < x < -1 || 1 < x < 5)
f[x_ /; (-5 < x < -1 || 1 < x < 5)] := x^2
is better
$\endgroup$
Nov 20, 2016 at 22:22
With
reg = ImplicitRegion[-5 < x < -1 || 1 < x < 5, x]
or
reg = Interval[{-5, -1}, {1, 5}]
do
Plot[x^2, {x} ∈ reg]
EDIT
This might work for v7:
Plot[If[-5 < x < -1 || 1 < x < 5, x^2], {x, -5, 5}]
Plot[x^2, {x} ∈ Interval[{-5, -1}, {1, 5}]]
seems particularly nice to code.
$\endgroup$
Nov 20, 2016 at 22:48
Another way is with the option RegionFunction
:
Plot[x^2, {x, -5, 5}, RegionFunction -> Function[x, -5 < x < -1 || 1 < x < 5]]