MathGroup Archive 2008

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

Search the Archive

Re: Converting a string to a variable name

  • To: mathgroup at smc.vnet.net
  • Subject: [mg90332] Re: Converting a string to a variable name
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Sun, 6 Jul 2008 07:18:52 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, UK
  • References: <g4ncqd$gh8$1@smc.vnet.net>

Aaron Fude wrote:

> Is it possible to create a variable whose name is contained in another
> variable or a string, something along the lines of
> 
> Table[ a="Var"<>ToString[i]; Variable[a] = i^2, {i, 1, 10}]
> 
> and end up with variables Var1, ..., Var10?

The function Set has the attributes HoldFirst, so we force the 
evaluation of its first argument before the assignment occurs.

The built-in function *Variables* (with an 's') returns a list so we 
extract the name with Part and convert the string into a symbol. Then 
the immediate assignment can be done as usual.

In[1]:= Table[a = "Var" <> ToString[i];
  Set[Evaluate[Variables[a][[1]] // ToExpression], i^2], {i, 1, 10}]

Out[1]= {1, 4, 9, 16, 25, 36, 49, 64, 81, 100}

In[2]:= Do[
  Print["Var" <> ToString[i] <> " =  ",
   "Var" <> ToString[i] // ToExpression], {i, 1, 10}]

During evaluation of In[2]:= Var1 =  1

During evaluation of In[2]:= Var2 =  4

During evaluation of In[2]:= Var3 =  9

During evaluation of In[2]:= Var4 =  16

During evaluation of In[2]:= Var5 =  25

During evaluation of In[2]:= Var6 =  36

During evaluation of In[2]:= Var7 =  49

During evaluation of In[2]:= Var8 =  64

During evaluation of In[2]:= Var9 =  81

During evaluation of In[2]:= Var10 =  100

Regards,
-- Jean-Marc


  • Prev by Date: Re: Relational Operators and Random Integers
  • Next by Date: Re: Relational Operators and Random Integers
  • Previous by thread: Re: Converting a string to a variable name
  • Next by thread: Automatic numbering