Re: Partition a list based on columns
- To: mathgroup at smc.vnet.net
- Subject: [mg119707] Re: Partition a list based on columns
- From: Ray Koopman <koopman at sfu.ca>
- Date: Sat, 18 Jun 2011 06:13:20 -0400 (EDT)
- References: <itcdai$d13$1@smc.vnet.net> <itek2d$s5q$1@smc.vnet.net>
On Jun 16, 9:09 pm, Ray Koopman <koop... at sfu.ca> wrote: > On Jun 16, 1:02 am, StatsMath <stats.ma... at gmail.com> wrote: >> >> [...] >> >> What would be a good way to line up elements in a list in a diagonal >> fashion, for ex: from Range[9] want to create the follwing matrix: >> >> 1 2 4 >> 3 5 7 >> 6 8 9 >> >> Thanks in advance! > > This will give an r x c matrix whose elements are > the integers 1...r*c in the positions you asked for: > > m[r_,c_] := With[{d = Which[ > r < c-1, Join[Range[ r ],Table[r,{c-2-r}],Range[ r ,1,-1]], > r > c-1, Join[Range[c-1],Table[c-1,{r-c}],Range[c-1,1,-1]], > True , Join[Range[c-2], Range[c-1,1,-1]]]}, > Partition[FoldList[Plus,0,d],c,1] + Range@r] > > m[3,5] //TableForm > > 1 2 4 7 10 > 3 5 8 11 13 > 6 9 12 14 15 Here's a better way to get an r x c matrix whose elements are the integers 1...r*c in the desired positions. To put the elements of a vector v in those positions, just change Range[r*c] to v. m[r_,c_] := Partition[Range[r*c][[ Ordering@SortBy[ Tuples@{Range@r,Range@c}, Tr] ]], c]