MathGroup Archive 2006

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

Search the Archive

Re: Convert from String to variable

  • To: mathgroup at smc.vnet.net
  • Subject: [mg70242] Re: Convert from String to variable
  • From: Peter Pein <petsie at dordos.net>
  • Date: Mon, 9 Oct 2006 01:55:56 -0400 (EDT)
  • References: <ega5d4$bpc$1@smc.vnet.net>

PengYu.UT at gmail.com schrieb:
> I want generate some code like below.
> 
> {a[0][0][0] -> a000, a[0][0][1] -> a001,
>    a[0][0][2] -> a002, a[0][1][0] -> a010,
>    a[0][1][1] -> a011, a[0][1][2] -> a012,
>    a[0][2][0] -> a020, a[0][2][1] -> a021,
>    a[0][2][2] -> a022, a[1][0][0] -> a100,
>    a[1][0][1] -> a101, a[1][0][2] -> a102,
>    a[1][1][0] -> a110, a[1][1][1] -> a111,
>    a[1][1][2] -> a112, a[1][2][0] -> a120,
>    a[1][2][1] -> a121, a[1][2][2] -> a122,
>    a[2][0][0] -> a200, a[2][0][1] -> a201,
>    a[2][0][2] -> a202, a[2][1][0] -> a210,
>    a[2][1][1] -> a211, a[2][1][2] -> a212,
>    a[2][2][0] -> a220, a[2][2][1] -> a221, a[2][2][2] -> a222}
> 
> I'm looking for an automated way to generate the assignments for
> a[i][j][k] (i = 1...n,j=1...n,k=1...n).
> 
> One way that I think of is
> Flatten[ Table[a[i][j][k] -> "a" <> ToString[i] <> ToString[j] <>
> ToString[k], {i, 0, 2}, {j, 0, 2}, {k, 0, 2}]].
> 
> But this method requires to convert the strings to variables. Is it
> possible to do this in Mathematica?
> 
> Are there any better solution to generate the assignment list?
> 
> Thanks,
> Peng
> 

Hi Peng,

near the bottom of the help entry for ToString you'll find a link to
ToExpression...

In[1]:=
Flatten[Table[a[i][j][k] -> ToExpression[StringJoin @@ Prepend[ToString
/@ {i, j, k}, "a"]], {i, 0, 2}, {j, 0, 2}, {k, 0, 2}]]
Out[1]=
{a[0][0][0] -> a000, a[0][0][1] -> a001, a[0][0][2] -> a002, a[0][1][0]
-> a010, a[0][1][1] -> a011,
  a[0][1][2] -> a012, a[0][2][0] -> a020, a[0][2][1] -> a021, a[0][2][2]
-> a022,
  a[1][0][0] -> a100, a[1][0][1] -> a101, a[1][0][2] -> a102, a[1][1][0]
-> a110,
  a[1][1][1] -> a111, a[1][1][2] -> a112, a[1][2][0] -> a120, a[1][2][1]
-> a121,
  a[1][2][2] -> a122, a[2][0][0] -> a200, a[2][0][1] -> a201, a[2][0][2]
-> a202,
  a[2][1][0] -> a210, a[2][1][1] -> a211, a[2][1][2] -> a212, a[2][2][0]
-> a220,
  a[2][2][1] -> a221, a[2][2][2] -> a222}
In[2]:=
Head[%[[1,2]]]
Out[2]=
Symbol

but I would prefer to do this more general:
Block[{n = Range[3] - 1, d = 4},
  Thread[#1 -> ToExpression[StringReplace[ToString[#1], "["|"]"->""]]]&
    [Nest[Flatten[(#1 /@ n & ) /@ #1] & , {a}, d]]]
-->
{a[0][0][0][0] -> a0000, a[0][0][0][1] -> a0001,
...
 a[2][2][2][1] -> a2221,  a[2][2][2][2] -> a2222}

If you plan to use this list of rules more than once, consider to wrap a
Dispatch around it.

Peter


  • Prev by Date: Re: Convert from String to variable
  • Next by Date: Re: Convert from String to variable
  • Previous by thread: Re: Convert from String to variable
  • Next by thread: Formal operations with vectors and scalars