I'm trying to plot the gradient field of a function in such a way that is possible to change it easily, only editing the function.
Consider the code:
xmin := -2; xmax := -xmin; ymin := -2; ymax := -ymin;
f[x_, y_] := x^2 + y^2
Plot3D[f[x, y], {x, xmin, xmax}, {y, ymin, ymax}]

So, the following code produces a very fancy result:
VectorPlot[{2 x, 2 y}, {x, xmin, xmax}, {y, ymin, ymax},
StreamPoints -> Coarse, StreamColorFunction -> Hue]

Since {D[f[x, y], x], D[f[x, y], y]} produces {2 x, 2 y} I tried to define
Gradf := {D[f[x, y], x], D[f[x, y], y]}
and use
VectorPlot[Gradf, {x, xmin, xmax}, {y, ymin, ymax},
StreamPoints -> Coarse, StreamColorFunction -> Hue]
but I got a lot of errors as
General::ivar: -1.99971 is not a valid variable. >>
General::stop: Further output of General::ivar will be suppressed during this calculation. >>
I really don't understand why it is not working.
Any idea how to solve this so I could only change the definition of f and plot again?




Gradf[x_, y_] = {D[f[x, y], x], D[f[x, y], y]}instead ofGradf := .... Then it works perfectly. See here – Öskå May 22 '14 at 23:46Derivativeof your function with thex = some value, instead of theVariablexbecause of theSetDelayed. So it says "-1.9something is not a valid variable" with which it can find the derivative. It's like sayingD[x,0]. – Öskå May 22 '14 at 23:48:=. – Sigur May 22 '14 at 23:49Gradfis going to be{2 x, 2y}". You need toClearAll@Gradfso Mathematica forgets it. – Öskå May 22 '14 at 23:51With[{gradient = Grad[f[x, y], {x, y}]}, VectorPlot[gradient, {x, xmin, xmax}, {y, ymin, ymax}, StreamPoints -> Coarse, StreamColorFunction -> Hue]]– murray May 24 '14 at 15:01