Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: How to unflatten an array ?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg112818] Re: How to unflatten an array ?
  • From: Sseziwa Mukasa <mukasa at jeol.com>
  • Date: Fri, 1 Oct 2010 05:43:52 -0400 (EDT)

On Sep 30, 2010, at 4:52 AM, Valeri Astanoff wrote:

> Good day,
> 
> Suppose I have a flat array like this :
> 
> {{1, 0, 1}, {1, 1, 1}, {1, 2, 3}, {2, 0, 5}...
> 
> and I want to get back to this "unflattened" form :
> 
> {{{{1, 0}, 1}, {{1, 1}, 1}, {{1, 2}, 3}}, {{{2, 0}, 5}...
> 
> What is the most efficient way to do it ?
> 
> 
> All I have found is this :
> 
> In[1]:= unflatten[arr : {{_, _, _} ..}] :=
> Module[{f},
> Scan[(f[#[[1]], #[[2]]] = #[[3]]) &, arr];
> Table[{{x, y}, f[x, y]},
> {x, arr[[All, 1]] // Union},
> {y, arr[[All, 2]] // Union}]
> ];
> 
> In[2]:= a1 = {{{{1, 0}, 1}, {{1, 1}, 1}, {{1, 2}, 3}},
> {{{2, 0}, 5}, {{2, 1}, 0}, {{2, 2}, 0}}, {{{3, 0}, 4},
> {{3, 1}, 5}, {{3, 2}, 2}}, {{{5, 0}, 1}, {{5, 1}, 3},
> {{5, 2}, 2}}};
> 
> In[3]:= a2 = Flatten /@ Flatten[a1, 1]
> 
> Out[3]= {{1, 0, 1}, {1, 1, 1}, {1, 2, 3}, {2, 0, 5},
> {2, 1, 0}, {2, 2, 0}, {3, 0, 4}, {3, 1, 5}, {3, 2, 2},
> {5, 0, 1}, {5, 1, 3}, {5, 2, 2}}
> 
> In[4]:= a3 = unflatten@a2
> 
> Out[4]= {{{{1, 0}, 1}, {{1, 1}, 1}, {{1, 2}, 3}},
> {{{2, 0}, 5}, {{2, 1}, 0}, {{2, 2}, 0}}, {{{3, 0}, 4},
> {{3, 1}, 5}, {{3, 2}, 2}}, {{{5, 0}, 1}, {{5, 1}, 3},
> {{5, 2}, 2}}}
> 
> In[5]:= a1 == a3
> 
> Out[5]= True
> 
> 
> Please help me to something faster for large arrays.

I would construct the desired result as:

Partition[{Most[#],Last[#]}&/@a2,3]

Comparing on a array of 10002 triples the timing of the two algorithms is

(Debug) In[244]:= a4 = RandomInteger[{-10, 10}, {100002, 3}];
First[Timing[unflatten[a4];]]
First[Timing[Partition[{Most[#], Last[#]} & /@ a4, 3];]]
(Debug) Out[245]= 1.39615
(Debug) Out[246]= 0.549411

Regards,
	Sseziwa


  • Prev by Date: Re: Mathematica calculates RSquared wrongly?
  • Next by Date: Re: 4 Gb are not enough ...
  • Previous by thread: Re: How to unflatten an array ?
  • Next by thread: Re: How to unflatten an array ?