Re: Symbol function, a question
- To: mathgroup at smc.vnet.net
- Subject: [mg90591] Re: Symbol function, a question
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Tue, 15 Jul 2008 06:16:23 -0400 (EDT)
- References: <g54om5$f1i$1@smc.vnet.net>
Hi, > Firstly, I create a variable > x95 = 100 > Now, I want to change the value of my variable x95 to 20 , > so I want to use some procedure like : > > Symbol["x" <> ToString[95]] = 20 > my idea is to make Mathematica write the term "x95" automatically for > me but when I use the Symbol function in this case, it gives me > automatically 100 and I don' t know how to call only x95. > Thank you if someone can give me a suggestion. I think this would (also) do what you want: Set @@ Append[ ToExpression["x" <> ToString[95], InputForm, Hold], 10 ] of course this can also be put into a function: SetAttributes[myset,HoldAll] myset[prefix_String,num_Integer,val_]:= Set @@ Append[ ToExpression[prefix <> ToString[num], InputForm, Hold], val ] which then can be called as: myset["x",95,10] As others have mentioned, you need to prevent the variable from being evaluated to it's value, this is why we need the three arguments form of ToExpression. The rest is just one of many ways to create the corresponding call to Set (which is the FullForm of =) without evaluating x95. With this method you don't need to convert the RHS of the Set to a string, which is probably more efficient and less error prone. One additional hint: In most cases it turns out to be more efficient to use DownValues like x[95] instead of variable names x95 if 95 is something that needs to be accessed programmatically. It also produces code that is much easier to write, read and understand. You can use these "variable names" even as variables in Solve, NSolve, NDSolve etc., so I hardly have found a situation where I would need x95 instead of x[95]. E.g.: Solve[{x[1] + 4 x[2] == 1, x[1] - 3 x[2] == 2}, {x[1], x[2]}] NDSolve[{x[1]'[t] == x[1][t] + 0.5 x[2][t], x[2]'[t] == x[2][t] + 0.5 x[1][t], x[1][0] == 1, x[2][0] == -1}, {x[1], x[2]}, {t, 0, 1}] hth, albert