MathGroup Archive 2009

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

Search the Archive

Re: Modify variable names in a loop

  • To: mathgroup at
  • Subject: [mg101785] Re: Modify variable names in a loop
  • From: Albert Retey <awnl at>
  • Date: Fri, 17 Jul 2009 05:02:35 -0400 (EDT)
  • References: <h3n515$1qm$>


> 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



  • Prev by Date: Re: Add syntax highlighting to own command
  • Next by Date: Re: Bug, quirk or expected behavior of Slot[]?
  • Previous by thread: Re: Modify variable names in a loop
  • Next by thread: Re: Modify variable names in a loop