I would like to use ToExpression
(or Symbol
) within Manipulate
. Specifically, when running Manipulate
, I want to build variables from strings, convert them to symbols (dynamic ones) and return values. But I guess I am missing something. Possibly very straight forward.
Here's an example:
a2 = 37; (*GLOBAL*)
Manipulate[
Module[{a1 = 1, a2 = 2, a3 = 3, a4 = 4},
Column[{text, var, ToExpression[text <> ToString@var],a1}]], {{text,
"a"}, {"a", "b"}}, {var, 1, 2, 1, ControlType -> SetterBar}]
So I set a global a2
(to visualize the effect), the rest is local and it returns:
If I change to a2
, the global value is retrieved in the third line, i.e. 37, see the screenshot on the right.
So I think the contexts are confusing me. In order to solve my problem, here's what I tried then: I created a Dynamic
x
outside the Manipulate
and well, consistently (to me), I can now use two different sliders to control the variables (both called x
) within Manipulate
, see here:
Column[{{Slider[Dynamic[x]], Dynamic[x]},
Manipulate[
Column[{
Style["Within Manipulate", Bold],
x, Dynamic[x],ToExpression[x], "",
Style["Context", Bold],
Context[x], Head[x],"",
Style["Converting String", Bold],
ToExpression["x"], Dynamic@ToExpression["x"],
ToExpression["Dynamic[x]", InputForm, Hold],
ToExpression["FE`x"], ToExpression["Global`x"],
ToExpression["x", InputForm, Dynamic]}],
{{x, 2.5}, 2, 3}]}]
resulting in: (note: running command in Mathematica directly returns context FE, whereas it returns FE
Global` using export)
So, my question is: is there an easy way within Manipulate
to go from strings to symbols? (outside Manipulate
, it works just as I expect it to)
Thanks in advance!
EDIT
To clarify: when I use a variable directly in Manipualte
(such as a1
) its (local) value is returned (i.e. 1
), if I use ToExpression["a1"]
(i.e. from string) it retrieves the global value. And whats confusing: ToExpression[a1]
yields local value.
So the question: how to retrieve the local value of a variable in Manipulate
when given the "name" (string) of the variable.
Manipulate
is just to show that "some" of thex
withinManipulate
actually depend on that - which is not what I want. Further, I addeda2=37
as a Global var to visualize what is happening, i.e. whereToExpression["a2"]
is referring to $\endgroup$