Re: Modify variable names in a loop
- To: mathgroup at smc.vnet.net
- Subject: [mg101785] Re: Modify variable names in a loop
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Fri, 17 Jul 2009 05:02:35 -0400 (EDT)
- References: <h3n515$1qm$1@smc.vnet.net>
Hi, > I would like to modify the variable name in a loop and assign values > to the variable. > > For[kk = 1, kk <= 3, kk++, > "output" <> ToString[Evaluate[kk]] = {kk,kk+1,kk+2}; > ]; > > I would like the following output > output1={1,2,3} > output2={2,3,4} > output3={3,4,5} > > Although, "output" <> ToString[Evaluate[kk]] evaluates as expected, it > does not let me assign values. Am I missing something here? yes: "output" <> ToString[1] gives the _string_ "output1" which is a very different object from the symbol output1. Only to the latter you can make assignments. You can transform the string to the symbol with Symbol["output1"] or ToExpression["output1"]. Whatever you choose, for an assignement you will have to struggle with the evaluation order. I think there is another active thread which deals with the problem. As has been suggested many times in this newsgroup, in almost every case you will be better off to use DownValues for one symbols instead of creating many distinct symbols, that is: Do[output[kk] = {kk,kk+1,kk+2},{k,3}]; and then use output[2] instead of output2 later in your code. I have only seen some quite exotic cases where this approach wouldn't work much better... hth, albert