Here is a very nice example from The Student's Introduction to MATHEMATICA.
Manipulate[Module[{x, y},
ContourPlot[Exp[-x^2 - y^2] + x y, {x, -1, 1}, {y, -1, 1},
Contours -> 20,
Epilog ->
Dynamic[{Arrow[{pt,
pt + {y - 2 E^(-x^2 - y^2) x, x - 2 E^(-x^2 - y^2) y} /. {x ->
pt[[1]], y -> pt[[2]]}}]}]
]],
{{pt, {.5, .5}}, Locator,
Appearance -> Graphics[{Red, Disk[]}, ImageSize -> 5]}]
Which produces a wonderful demonstration.
My next step was to try the following:
Clear[x, y, f];
f = E^(-x^2 - y^2) + x y;
Grad[f, {x, y}];
Then in the next cell, I tried:
Manipulate[Module[{x, y},
ContourPlot[f, {x, -1, 1}, {y, -1, 1},
Contours -> 20,
Epilog ->
Dynamic[{Arrow[{pt,
pt + Grad[f, {x, y}] /. {x -> pt[[1]], y -> pt[[2]]}}]}]
]],
{{pt, {.5, .5}}, Locator,
Appearance -> Graphics[{Red, Disk[]}, ImageSize -> 5]}]
Which gave only this:
I gave Evaluate a try but that didn't work. So I tried removing the Module.
Manipulate[
ContourPlot[f, {x, -1, 1}, {y, -1, 1},
Contours -> 20,
Epilog ->
Dynamic[{Arrow[{pt,
pt + Grad[f, {x, y}] /. {x -> pt[[1]], y -> pt[[2]]}}]}]
],
{{pt, {.5, .5}}, Locator,
Appearance -> Graphics[{Red, Disk[]}, ImageSize -> 5]}]
And that worked.
But try typing
x=12
in the next cell and watch what happens to the arrow.
Finally I tried wrapping everything with a DynamicModule to see if it would prevent the x=12 issue in the notebook. First, this cell.
Clear[x, y, f];
f = E^(-x^2 - y^2) + x y;
Grad[f, {x, y}];
Then:
DynamicModule[{x, y},
Manipulate[
ContourPlot[f, {x, -1, 1}, {y, -1, 1},
Contours -> 20,
Epilog ->
Dynamic[{Arrow[{pt,
pt + Grad[f, {x, y}] /. {x -> pt[[1]], y -> pt[[2]]}}]}]
],
{{pt, {.5, .5}}, Locator,
Appearance -> Graphics[{Red, Disk[]}, ImageSize -> 5]}]]
This only produced:
As folks know, there has been a lot of discussion on not using Module inside of Manipulate and this is probably a good example of why not, but there is a lot of stuff happening here that I don't understand and could use some discussion explaining some of the issues:
Why does Dynamic in the first code just update the arrow and not the contour plot.
Why doesn't
f = E^(-x^2 - y^2) + x y;
andGrad[f, {x, y}];
work in the second piece of code?Why doesn't DynamicModule work in the last piece of code?
And what is the best way to protect the arrow if a student type x=12 in their notebook?