| 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: , |
|