MathGroup Archive 2009

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

Search the Archive

Re: defining consecutive variables

  • To: mathgroup at smc.vnet.net
  • Subject: [mg99450] Re: defining consecutive variables
  • From: Pillsy <pillsbury at gmail.com>
  • Date: Wed, 6 May 2009 05:21:53 -0400 (EDT)
  • References: <gtp199$joi$1@smc.vnet.net>

On May 5, 5:35 am, Jason <jbig... at uoregon.edu> wrote:
> I have a code where I need to define a large number of variables as matri=
ces, called q1,q2,q3......qn. I'd like to be able to define them all withou=
t writing out n assignment lines, so a Do loop seems appropriate to me but =
I don't know how to assign sequential variable names. This gets the job don=
e but it is really ugly IMO

Well, in your shoes, I would avoid variable names like these. Instead,
I'd make these expressions with the head "q", and use

q[1], q[2], ..., q[n]

as my variables if at all possible. Then I could easily assign them
like so:

With[{qs = Array[q, 3]},
  qs = Table[n^3, {n, 3}]];
{q[1], q[2], q[3]}

which returns

{1, 8, 27}

If you really insist on having the variables be q1, q2, q3... though,
then you can do something a little less clunky using Symbol[] instead
of ToExpression[], like so:

With[{qs = Table[Symbol[StringJoin["q", ToString[n]]], {n, 3}]},
   qs = Table[n^3, {n, 3}]]

This will rapidly get annoying as you'll have a much harder time
cleaning up with Clear[] and ClearAll[], and it will be much harder to
scope assignments to the variables with Block[].

Cheers,
Pillsy


  • Prev by Date: Re: Making a user interface
  • Next by Date: Re: Making a user interface
  • Previous by thread: Re: defining consecutive variables
  • Next by thread: Re: defining consecutive variables