Mathematica Plot with Manipulate Does Not Show Exit

At first I tried to visualize a function with 4 parameters using Plot3D and manipulate the sliders (with two parameters controlled by sliders, and the others in the "xy" plane). However, I do not get any output when my parameters without a drawing are controlled by Manipulation?

The following example 1d example reproduces what I see in a more complex plot attempt:

Clear[g, mu] g[ x_] = (x Sin[mu])^2 Manipulate[ Plot[ g[x], {x, -10, 10}], {{mu, 1}, 0, 2 \[Pi]}] Plot[ g[x] /. mu -> 1, {x, -10, 10}] 

The area with a fixed value of mu has the expected parabolic output in the automatically selected graphic range {0.70}, while the manipulation graph is empty in the range {0, 1}.

I suspected that PlotRange was not selected with good defaults when using the mu slider control, but adding to PlotRange manually does not show the output either:

 Manipulate[ Plot[ g[x], {x, -10, 10}, PlotRange -> {0, 70}], {{mu, 1}, 0, 2 \[Pi]}] 
+4
source share
2 answers

This is because Manipulate parameters are local.

mu in Manipulate[ Plot[ g[x], {x, -10, 10}], {{mu, 1}, 0, 2 \[Pi]}] is different from the global mu that you clear in the previous line.

I suggest using

 g[x_, mu_] := (x Sin[mu])^2 Manipulate[Plot[g[x, mu], {x, -10, 10}], {{mu, 1}, 0, 2 \[Pi]}] 

The following works, but it continues to change the value of the global variable, which may cause surprises later if you do not pay attention, therefore I do not recommend:

 g[x_] := (x Sin[mu])^2 Manipulate[ mu = mu2; Plot[g[x], {x, -10, 10}], {{mu2, 1}, 0, 2 \[Pi]} ] 

It may happen that you are Clear[mu] , but find that it gets the value when you scroll the Manipulate object in the view.

+8
source

Another way to overcome the localization of Manipulate is to call the function inside Manipulate[] :

 Manipulate[Module[{x,g}, g[x_]=(x Sin[mu])^2; Plot[g[x], {x, -10, 10}]], {{mu, 1}, 0, 2 \[Pi]}] 

or even

 Manipulate[Module[{x,g}, g=(x Sin[mu])^2; Plot[g, {x, -10, 10}]], {{mu, 1}, 0, 2 \[Pi]}] 

Both of them give

Define g inside manipulate

Module[{x,g},...] prevents unwanted side effects from the global context. This allows a simple definition of g: I had Manipulate[] ed graphs with dozens of custom parameters that can be cumbersome to pass all of these parameters as arguments to the function.

+2
source

All Articles