2
$\begingroup$

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?

$\endgroup$
4
  • 1
    $\begingroup$ May be like this Flatten /@ ({column1, data, column7, column8} // Transpose) $\endgroup$ Commented Mar 8, 2017 at 11:09
  • $\begingroup$ @ Anjan Kumar: This is great ... put it into an answer, although it is a one-liner. $\endgroup$
    – mrz
    Commented Mar 8, 2017 at 11:13
  • $\begingroup$ Also possible duplicates: (189), (3069) $\endgroup$
    – Mr.Wizard
    Commented Mar 8, 2017 at 11:50
  • $\begingroup$ @Mr.Wizard: Thank you for your answer and two links. $\endgroup$
    – mrz
    Commented Mar 8, 2017 at 13:56

3 Answers 3

2
$\begingroup$
☺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

$\endgroup$
2
$\begingroup$
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}}*)
$\endgroup$
1
$\begingroup$

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]
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.