Mathematica 9 is now available
Student Support Forum
-----
Student Support Forum: 'Retrieve a variable name from a string' topicStudent Support Forum > General > "Retrieve a variable name from a string"

Next Comment >Help | Reply To Topic
Author Comment/Response
Hannes Svardal
12/22/11 08:11am

Hi all,

I want to create a string using some string operations, convert it into a variable name and assign a value to it. This works if the corresponding variable is not yet assigned, but not if it already has a value assigned. If the variable already has a value assigned to it I want to overwrite it.

Imagine I have the string "b", now I want to assign a value to the variable b, e.g. b = 5, without directly typing b, but only "b".

string = "b";

If the symbol b does not yet have a value associated, this works without problems. I can convert the string to a Symbol with "ToExpression[string]" and evaluate this so that the result can be assigned with a numerical value:

Evaluate[ToExpression[string]] = 5;

Now we have :

In[242]:= InputForm[string]

Out[242]//InputForm=
"b"

In[241]:= b

Out[241]= 5

The problem arises when we want to set an other value to b now. I do not see a way how to do this starting from the string. This is because the string is either "b", or if I convert it to an expression it is immediately set to be 5, but I cannot retrieve b. For instance:

In[243]:= Evaluate[ToExpression[string]] = 1;

During evaluation of In[243]:= Set::setraw: Cannot assign to raw object 5. >>

Here, the lhs is evaluated to 5. How can I evaluate string to give b, so that I can assign a new numerical value to it?

Thanks in advance,
Hannes

URL: ,

Subject (listing for 'Retrieve a variable name from a string')
Author Date Posted
Retrieve a variable name from a string Hannes Svardal 12/22/11 08:11am
Re: Retrieve a variable name from a string Patrick 12/29/11 4:38pm
Re: doesn't seem to work for me Hannes Svardal 01/05/12 04:20am
Re: Retrieve a variable name from a string jf 01/05/12 11:21am
Next Comment >Help | Reply To Topic