Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2008

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

Search the Archive

Re: Debracketing array symbols

  • To: mathgroup at smc.vnet.net
  • Subject: [mg92096] Re: [mg92079] Debracketing array symbols
  • From: Daniel Lichtblau <danl at wolfram.com>
  • Date: Sat, 20 Sep 2008 04:56:55 -0400 (EDT)
  • References: <200809190917.FAA15137@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++.

If the conversion is to happen within Mathematica, use a simple 
replacement rule. Below we do this to get either subscripts or 
concatenated variable names.

In[17]:= {{W[1, 1], W[1, 2]}, {W[2, 1], W[2, 2]}} /.
   W[aa__] :> Subscript[W, aa]
Out[17]= {{Subscript[W, 1, 1], Subscript[W, 1, 2]}, {Subscript[W, 2,
   1], Subscript[W, 2, 2]}}

In[21]:= {{W[1, 1], W[1, 2]}, {W[2, 1], W[2, 2]}} /.
   W[aa__] :>
     ToExpression[StringJoin[ToString[W], Map[ToString, {aa}]]]
Out[21]= {{W11, W12}, {W21, W22}}

If you intend to do the replacement in C++, I'd say you are better off 
coding it in C++ rather than coding in Mathematica and then translating.

Daniel Lichtblau
Wolfram Research



  • Prev by Date: Re: shooting method
  • Next by Date: Re: Functional Programming?
  • Previous by thread: Debracketing array symbols
  • Next by thread: Re: Debracketing array symbols