# Tricky use of MeshFunction

MeshFunctions helps to get an approximation of the roots

Plot[Sin[x], {x, -5, 5}, MeshFunctions -> {#2 &}, Mesh -> {{0}}, MeshStyle -> {PointSize[Large]}] of the plotfunction, wish is accessed as a pure function #2&

How can I detect points of a given slope of (#2&) in the same way? Thanks!

• Thank you, I have to go your proposed way. Jul 7, 2018 at 10:05
• I was clearly wrong though, so I deleted the comment. Jul 7, 2018 at 10:35
• @Szabolcs I don't think so. Your comment concerning the derivative of a pure function inside stills holds. Jul 7, 2018 at 12:14
• I mean, I forgot that the mesh can be specified not only in terms of the y coordinate but also the x coordinate. Then we can use an explicit form of the derivative function, as Brett did. Jul 7, 2018 at 15:43

If you're only plotting one function at a time you could use the following:

f = Sin[x];

Plot[f, {x, -5, 5}, MeshFunctions -> {Function[x, Evaluate[D[f, x]]]},
Mesh -> {{-0.5}}, MeshStyle -> {PointSize[Large]}] The mesh function uses Evaluate since we need to make sure the derivative is taken with a symbolic value of $x$, before it starts receiving numeric values.

• Thank you for your suggestion to use explicit functions. Jul 7, 2018 at 10:06

Here is an approach that follows @Szabolcs' suggestion in comments, i.e of plotting the derivative of the function to extract the values, then reporting those values back to a plot of the original function:

Clear[f]
f[x_?NumericQ] := Sin[x]

pts = Cases[
Normal@
Plot[
D[f[t], t] /. t -> x, {x, -5, 5},
MeshFunctions -> {#2 &}, Mesh -> {{-0.5}}
], p_Point :> First[p], All];

tangents = Function[{x}, f[#1] + #2 (x - #1) & @@@ pts];

Plot[
{f[x], Style[tangents[x], GrayLevel[0.5], Dashed]},
{x, -5, 5}, PlotRange -> 1.2,
Epilog -> {
PointSize[Large], Red,
Point[pts /. {x_Real, y_Real} :> {x, f[x]}]
},
ImageSize -> Large
] I have defined the function in question as something that only evaluates when given numeric input to show that this should work with reasonable functions more complex than the simple Sin[x] as well.

An alternative way to find those points is to use the NDSolve machinery and WhenEvent:

Reap[
NDSolve[
{D[y[x], x] == f'[x], y == f, WhenEvent[y'[x] == -0.5, Sow[x]]},
y, {x, -5, 5}
]
][[2, 1]]

(* Out: {-2.0944, -4.18879, 2.0944, 4.18879} *)

Plot[
f[x], {x, -5, 5},
Epilog -> {
PointSize[Large], Red,
Point[{#1, f[#1]} & /@ ptsNDSolve]
}
] • Thank you for your very helpful hints. Jul 7, 2018 at 10:07