MathGroup Archive 2003

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: How to convert string to variable name


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


  • Prev by Date: Re: Problem :mathematica building help browser index
  • Next by Date: Re: Re: nth differences
  • Previous by thread: Re: Re: How to convert string to variable name
  • Next by thread: Re: Re: How to convert string to variable name