MathGroup Archive 2008

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

Search the Archive

Re: Debracketing array symbols

  • To: mathgroup at smc.vnet.net
  • Subject: [mg92095] Re: Debracketing array symbols
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Sat, 20 Sep 2008 04:56:44 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, UK
  • References: <gavqna$eon$1@smc.vnet.net>

carlos at colorado.edu wrote:
> Hi,
> 
> For a class project I generate 1D and 2D arrays of arbitrary size with
> entries <letters>[i] and <letters>[i,j] that I need then to convert
> to <letter>i and <letter>ij for export to other languages that do not
> allow brackets in symbol names. E.g.
> 
> 1D:  {A[1],A[2],A[3],A[4]} -> {A1,A2,A3,A4}
> 
> 2D:  {{W[1,1],W[1,2]},{W[2,1],W[2,2]}}  -> {{W11,W12},{W21,W22}}
> 
> Question: would this be the simplest way to do it?
> 
> DebracketArrayEntries[Wm_]:=Module[{dim,rep,i,j,n,m,s,Wr},
>     rep={"["->"","]"->"",","->""," "->""}; Wr=Wm;
>     dim=Length[Dimensions[Wm]];
>     If [dim==1,n=Length[Wm]; Print["n=",n];
>         For [i=1,i<=n,i++, s=ToString[Wm[[i]]];
>              Wr=Wr/.Wm[[i]]->Symbol[StringReplace[s,rep]] ]];
>     If [dim==2,{n,m}=Dimensions[Wm];
>         For [i=1,i<=n,i++, For[j=1,j<=m,j++, s=ToString[Wm[[i,j]]];
>              Wr=Wr/.Wm[[i,j]]->Symbol[StringReplace[s,rep]] ]]];
>     Return[Wr]];
> 
> The procedural style is to simplify conversion to C++.

I am not sure to have understood what you meant by "simplest way." Are 
you looking for some Mathematica code that it is the as easy as possible 
to translate in procedural languages, or the simplest, most efficient, 
Mathematica code possible?

For the latter, the function

Map[ToExpression[
     StringReplace[ToString[#], {"[" | "]" | "," | " " -> ""}]] &, #, {-2}]&

will convert indexed variables stored in lists of any dimensions into 
the desired non-indexed form, while keeping the array structure intact. 
For instance,

In[1]:= DebracketArrayEntries[Wm_] :=
  Map[ToExpression[
     StringReplace[ToString[#], {"[" | "]" | "," | " " -> ""}]] &,
   Wm, {-2}]

d[1] = Array[A, 4];
d[2] = Array[W, {2, 2}];
d[3] = Array[Z, {2, 2, 3}];
d[4] = Array[U, {2, 2, 3, 2}];

DebracketArrayEntries /@ Array[d, 4]

Out[6]= {{A1, A2, A3,
   A4}, {{W11, W12}, {W21,
    W22}}, {{{Z111, Z112, Z113}, {Z121, Z122, Z123}}, {{Z211, Z212,
     Z213}, {Z221, Z222,
     Z223}}}, {{{{U1111, U1112}, {U1121, U1122}, {U1131,
      U1132}}, {{U1211, U1212}, {U1221, U1222}, {U1231,
      U1232}}}, {{{U2111, U2112}, {U2121, U2122}, {U2131,
      U2132}}, {{U2211, U2212}, {U2221, U2222}, {U2231, U2232}}}}}

Regards,
-- Jean-Marc


  • Prev by Date: Re: the graphic of a function
  • Next by Date: Re: Functional programming?
  • Previous by thread: Re: Debracketing array symbols
  • Next by thread: Re: Debracketing array symbols