Re: Debracketing array symbols
- To: mathgroup at smc.vnet.net
- Subject: [mg92119] Re: Debracketing array symbols
- From: magma <maderri2 at gmail.com>
- Date: Sat, 20 Sep 2008 05:01:16 -0400 (EDT)
- References: <gavqna$eon$1@smc.vnet.net> <gavt05$g4l$1@smc.vnet.net>
On Sep 19, 11:56 am, dh <d... at metrohm.ch> wrote: > Hi carlos, > > you could e.g. try: > > {A[1],A[2],A[3],A[4]}/.x_[y_]:>Symbol[ToString[x]<>ToString[y]] > > hope this helps, Daniel > > > > car... 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=ToStri= ng[Wm[[i,j]]]; > > Wr=Wr/.Wm[[i,j]]->Symbol[StringReplace[s,r= ep]] ]]]; > > Return[Wr]]; > > > The procedural style is to simplify conversion to C++. > > -- > > Daniel Huber > > Metrohm Ltd. > > Oberdorfstr. 68 > > CH-9100 Herisau > > Tel. +41 71 353 8585, Fax +41 71 353 8907 > > E-Mail:<mailto:d... at metrohm.com> > > Internet:<http://www.metrohm.com> This is a perfect showcase of the expressive power of Mathematica versus traditional procedural programming. Daniel Huber's one line solution using ReplaceAll simply replaces all occurrences of something in form of x[y] with a customized new symbol. Anybody can compare this with the proposed procedural code with all its ifs and buts, but do not waste your whole weekend :-) PS: Huber's code deals with the 1D case. Going to 2D should be almost obvious for everybody at this point.