Re: How to convert string to variable name
- To: mathgroup at smc.vnet.net
- Subject: [mg39892] Re: How to convert string to variable name
- From: atelesforos at hotmail.com (Orestis Vantzos)
- Date: Sun, 9 Mar 2003 18:40:14 -0500 (EST)
- References: <b49n66$fdc$1@smc.vnet.net> <b4f5fq$7du$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Bob, if you want to get to that kind of programming (scripting Mathematica inside Mathematica) it pays to understand the way things are evaluated in Mathematica. Symbol["x"] IS indeed the 'natural' way to create a symbol named x. To answer your question on why Symbol["x"]=13 does not work, try ToExpression["x"]=13. ..it doesn't work either. The answer is that Set(=) has the Attribute HoldFirst which keeps the left-hand side of the assignment from being created. A direct solution is Evaluate[Symbol["x"]]=13 or Evaluate[ToExpression["x"]]=13. Now, you seem to believe that ToExpression["x=13"] is the way to do it. I do not agree: the string inside ToExpression does not interact properly with scoping constructs like Module,With and asignments. Try: With[{a=13},ToExpression["x=a"]] or assigntox[n_]:=ToExpression["x=n"] The scoping constructs just can't see the symbols inside the string! I think the best way to go is something like: With[{var=Symbol["x"]}, ...stuff with var... ] Orestis Bob Harris <NspamITmeLION at MINDnotSPRING.COM> wrote in message news:<b4f5fq$7du$1 at smc.vnet.net>... > I wrote: > >> ... for a given string, how can I assign to the variable whose name is > >> defined by that string? > > and Hermann Schmitt replied: > > I would do it the following way: > > ToExpression["z = ....."]; > > Thanks, that appears to be what I want. I just have to build a string that > contains the entire assignment. > > A couple people suggested using Symbol[], but I don't see how that would > work. For example, > > Symbol["x"] = 13 > > doesn't create a symbol x with value 13. Instead, it simply produces an > error message informing me that "Tag Symbol in Symbol["x"] is Protected." > > Thanks, > Bob H