MathGroup Archive 2009

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

Search the Archive

Re: defining consecutive variables

  • To: mathgroup at smc.vnet.net
  • Subject: [mg99481] Re: defining consecutive variables
  • From: Bill Rowe <readnews at sbcglobal.net>
  • Date: Wed, 6 May 2009 05:27:41 -0400 (EDT)

On 5/5/09 at 5:37 AM, jbiggs2 at uoregon.edu (Jason) wrote:

>I have a code where I need to define a large number of variables as
>matrices, called q1,q2,q3......qn. I'd like to be able to define
>them all without 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 done but it is really ugly IMO


>f[x_] := Table[x RandomReal[], {n, 5}, {np, 5}](*for example*)

>Do[ToExpression["q" <> ToString[n] <> "=f[n]"], {n, 0, 40}]

>at the end of which I have 41 matrices which I can call as q0,q1,
>etc. Is this the best way to accomplish this task?

The code below illustrates how this can be done. I've limited
the number of variables created to 5 and used integer data
simply to make it easy to show the code works. The same
principle can be used for any list of data. Note, this solution
assumes there are no existing variables with assigned values
with the same names. If this is the case, this code won't work.

In[1]:= MapThread[
   Set[#1, #2] &, {Table[ToExpression["a" <> ToString[n]], {n,
5}], Range[5]}];

In[2]:= a1
Out[2]= 1

In[3]:= a5
Out[3]= 5




  • Prev by Date: Given a matrix, find position of first non-zero element in each row
  • Next by Date: Re: Making a user interface
  • Previous by thread: Re: defining consecutive variables
  • Next by thread: Re: defining consecutive variables