Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mathematica Plot with Manipulate shows no output

I was initially attempting visualize a 4 parameter function with Plot3D and Manipulate sliders (with two params controlled by sliders and the other vary in the "x-y" plane). However, I'm not getting any output when my non-plotted parameters are Manipulate controlled?

The following 1d plot example replicates what I'm seeing in the 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 Plot with a fixed value of mu has the expected parabolic output in the {0,70} automatically selected plotrange, whereas the Manipulate plot is blank in the {0, 1} range.

I was suspecting that the PlotRange wasn't selected with good defaults when the mu slider control was used, but adding in a PlotRange manually also shows no output:

Manipulate[ Plot[ g[x], {x, -10, 10}, PlotRange -> {0, 70}], {{mu, 1}, 0, 2 \[Pi]}]
like image 739
Peeter Joot Avatar asked Oct 31 '11 13:10

Peeter Joot


2 Answers

This is because the Manipulate parameters are local.

The mu in Manipulate[ Plot[ g[x], {x, -10, 10}], {{mu, 1}, 0, 2 \[Pi]}] is different from the global mu you clear on 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 too, but it keeps changing the value of a global variable, which may cause surprises later unless you pay attention, so I don't recommend it:

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 Clear[mu], but find that it gets a value the moment the Manipulate object is scrolled into view.

like image 195
Szabolcs Avatar answered Nov 15 '22 14:11

Szabolcs


Another way to overcome Manipulate's localization is to bring the function inside the 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 which give

Define g inside manipulate

Module[{x,g},...] prevents unwanted side-effects from the global context. This enables a simple definition of g: I've had Manipulate[]ed plots with dozens of adjustable parameters, which can be cumbersome when passing all those parameters as arguments to the function.

like image 24
JxB Avatar answered Nov 15 '22 12:11

JxB