If I have a variable x := "a".
Is there a way I can use it to assign a value to a, by just referring to x?
If I try Evaluate[x]=4 I get error messages about Tag Times in x Null is protected.
I would like some way of having it execute a = 4.
Asked
Active
Viewed 203 times
1
Karsten7
- 27,448
- 5
- 73
- 134
Keith Sloan
- 11
- 1
1 Answers
1
adding one more and summarizing comments
ToExpression[x <> "=" <> ToString[10]];
or
ToExpression[StringJoin @@ ToString /@ {x, "=", 3.14}]
from: @LeonidShifrin
ToExpression[x, StandardForm, Function[var, var = 42, HoldFirst]]
@belisarius approach only works once:
Evaluate@Symbol[x] = 1
after "a" has a value, Symbol[x] returns the value so this breaks if you try to use it more than once.
@kuba proposes using TagSetDelayed x:
x := "a"
x /: Set[x, y_] := Set[a, y]
which will let you simply do:
x=3
with the result being assignment of "a" {x,a} -> {"a",3}
george2079
- 38,913
- 1
- 43
- 110
x = "a"; Evaluate@Symbol[x] = 1; a– Dr. belisarius Mar 09 '15 at 16:11Hold[x]/.OwnValues[x]/.Hold[var_]:>(var = 4)assuming thatais a symbol. If a is a string name, then:ToExpression[x, StandardForm, Function[var, var=4, HoldFirst]]. – Leonid Shifrin Mar 09 '15 at 16:17x /: Set[x, y_] := Set[a, y]? – Kuba Mar 09 '15 at 18:46Print[cols] l := Length[cols] Print[l] ClearAll[ra, assign] assign[symbols_, idx_, val_] := symbols[[{idx}]] /. _[x_] :> (x = val) symbols = Hold @@ cols; (*symbols=Hold[ra,dec,z]*) Print["Assign"] assign [symbols, 1, 4]; ra– Keith Sloan Mar 09 '15 at 20:54