2

I want to produce a table structure, with 7 rows and 8 columns.

SeedRandom[123];

column1 = RandomInteger[{10, 20}, 7]

 {17, 14, 20, 20, 10, 12, 16}

(*table with 7 rows and 5 columns to which column 1 should be prepended
  and column 7 and column 8 appended *)

data = RandomInteger[{10, 20}, {7, 5}]

{{17, 19, 18, 13, 19}, 
 {18, 20, 15, 12, 20}, 
 {16, 12, 16, 12, 10}, 
 {14, 11, 17, 16, 18}, 
 {13, 16, 16, 14, 20}, 
 {16, 15, 13, 15, 17},
 {15, 13, 17, 11, 16}}

column7 = RandomInteger[{10, 20}, 7]

 {14, 16, 16, 20, 10, 19, 19}

column8 = RandomInteger[{10, 20}, 7]

 {17, 19, 14, 17, 17, 17, 20}

The resulting table is:

table = Array[0 &, {7, 8}];

Table[
 table[[i]] = Flatten@{column1[[i]], data[[i]], column7[[i]], column8[[i]]}
 , {i, 1, 7}
 ]


{{17, 17, 19, 18, 13, 19, 14, 17},
 {14, 18, 20, 15, 12, 20, 16, 19}, 
 {20, 16, 12, 16, 12, 10, 16, 14}, 
 {20, 14, 11, 17, 16, 18, 20, 17}, 
 {10, 13, 16, 16, 14, 20, 10, 17}, 
 {12, 16, 15, 13, 15, 17, 19, 17}, 
 {16, 15, 13, 17, 11, 16, 19, 20}}

How can that result be obtained by using

a) combination of Prepend and/or Append
b) Transpose

Does another solution exists?

mrz
  • 11,686
  • 2
  • 25
  • 81

3 Answers3

2
☺1 = ## & @@@ # & /@ ({##}) &;

Mathematica graphics

☺1[column1, data, column7, column8] // MatrixForm

Mathematica graphics

or

☺2 = {#, ## & @@ (#2), ##3} &;

Mathematica graphics

☺3 = Transpose@Fold[Append, Prepend[Transpose@#2, #1], {##3}] &;
☺4 = Transpose@Prepend[Fold[Append, Transpose@#2, {##3}], #1] &;

☺1[##] == ☺2[##] == ☺3[##] ==☺4[##] &[column1, data, column7, column8]

True

kglr
  • 394,356
  • 18
  • 477
  • 896
2
Flatten /@ ({column1, data, column7, column8} // Transpose)

(*{{17, 17, 19, 18, 13, 19, 14, 17},
 {14, 18, 20, 15, 12, 20, 16, 19}, 
 {20, 16, 12, 16, 12, 10, 16, 14}, 
 {20, 14, 11, 17, 16, 18, 20, 17}, 
 {10, 13, 16, 16, 14, 20, 10, 17}, 
 {12, 16, 15, 13, 15, 17, 19, 17}, 
 {16, 15, 13, 17, 11, 16, 19, 20}}*)
Anjan Kumar
  • 4,979
  • 1
  • 15
  • 28
1

I think this question should probably be marked as a duplicate but for the time being:

Join[{column1}, data\[Transpose], {column7}, {column8}]\[Transpose]

Using columnAttach2 from Building matrices by attaching vectors (columns) and matrices

columnAttach2[column1, data, column7, column8]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371