Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define control as variable in Mathematica

When I use Manipulate I can do:

Manipulate[x, {u, 1, 10}]

In reality my controls are many and complicated, so I would prefer to take their definition out of the Manipulate expression, like that:

control = {u, 1, 10}
Manipulate[x, control]

But that does result in a an error:

Manipulate argument control does not have the correct form for a \
variable specification.

Why doesn't it work that way?

like image 678
Ludwig Weinzierl Avatar asked Aug 21 '11 14:08

Ludwig Weinzierl


People also ask

How do you make a multivariable function in Mathematica?

For functions of two or more variables we just use a comma in between each variable and make sure to use the underscore i.e for two variables it becomes f[x_,y_]:= and for three it becomes f[x_,y_,z_]:= and so forth.

What is manipulate command in Mathematica?

The single command Manipulate lets you create an astonishing range of interactive applications with just a few lines of input.

What does == mean in Mathematica?

Equal (==)—Wolfram Language Documentation.


2 Answers

Manipulate has the HoldAll attribute. You can force control to evaluate and everything works ok

control = {u, 1, 10};
Manipulate[x[u], Evaluate[control]]

The problem with this is that the variable u is not properly localised, so if you have already set, e.g., u=1 somewhere, then the Manipulate will return an error.

It might be better if you use appropriate scoping constructs such as With or DynamicModule depending on exactly what you're trying to do.

This is maybe overkill, but it ensures that u is local and moves control outside of the manipulate:

DynamicModule[{u}, With[{control = {u, 1, 10}}, Manipulate[x[u], control]]]
like image 131
Simon Avatar answered Sep 30 '22 20:09

Simon


This

con = {u, 1, 10};
Manipulate[
 u,
 Evaluate@con
 ]

does work. I suppose it doesn't work without the Evaluate because

Attributes[Manipulate]

shows that Manipulate has the attribute HoldAll (but I may be wrong). To see the effect of this attribute, try this:

SetAttributes[f, HoldAll]
f[con]
f[Evaluate@con]
g[con]
(*
f[con]
f[{u, 1, 10}]
g[{u, 1, 10}]
*)

Thus, it appears that due to the HoldAll atribute, Manipulate simply does not see "inside" con unless you explicitly evaluate it.

like image 28
acl Avatar answered Sep 30 '22 20:09

acl