From: Bob Hanlon on 18 Jul 2010 01:06 TF[m_] := Flatten[Transpose[m]] Combine[m1_, m2_] := Partition[Join[m1 // TF, m2 // TF], Length[m1]] // TF Combine2[m1_, m2_] := Flatten[Transpose[Join[Transpose[m1], Transpose[m2]]]] Combine3[m1_, m2_] := Flatten[Riffle[m1, m2]] m1 = Array[x, {3, 4}]; m2 = Array[y, {3, 4}]; Combine[m1, m2] == Combine2[m1, m2] == Combine3[m1, m2] True Bob Hanlon ---- Sam Takoy <sam.takoy(a)yahoo.com> wrote: ============= Hi, Given two matrices of equal height, what's the best way to combine them. Here's what I did TF[m_] := Flatten[Transpose[m]] Combine[m1_, m2_] := Partition[Join[m1 // TF, m2 // TF], Length[m1]] // T Surely there's a better way of doing it. Thanks!
From: Murray Eisenberg on 18 Jul 2010 01:07
First, unless I've missed something, it's not so easy find out how to do this by searching the documentation. Second, I always hesitate to deem a method "the best way" to do something. But Join with a third argument designating joining at "level" 2 does the trick nicely. This is documented twice on page ref/Join, first in the Scope section and then again in the Applications section. Example, like those: m1 = {{a,b,c},{d,e,f},{g,h,i}}; m2 = {{x,y}, {u,v}, {z,w}}; wider = Join[m1, m2, 2] Thus there is no need to resort to the "trick" of using Transpose. Third, the difficulty here is, to my mind, a limitation of Mathematica's inherent lack of any true array structure but rather just the one-dimensional structure of lists. Higher-order arrays need to be built more or less explicitly from lists. And that means the seemingly artificial way of treating questions such as yours, by means of a "level" specification. In a language that has a full-fledged development of arrays of any order (e.g., APL and, especially, J), such things as you ask are often easier, and more general, to handle. On 7/17/2010 8:16 AM, Sam Takoy wrote: > Hi, > > Given two matrices of equal height, what's the best way to combine them. > Here's what I did > > TF[m_] := Flatten[Transpose[m]] > Combine[m1_, m2_] := > Partition[Join[m1 // TF, m2 // TF], Length[m1]] // T > > > Surely there's a better way of doing it. > > Thanks! > -- Murray Eisenberg murray(a)math.umass.edu Mathematics & Statistics Dept. Lederle Graduate Research Tower phone 413 549-1020 (H) University of Massachusetts 413 545-2859 (W) 710 North Pleasant Street fax 413 545-1801 Amherst, MA 01003-9305 |