# How to combine the tables in the following way?

Consider two tables

tab1 = RandomReal[{0, 1}, {5, 4}]
tab2 = RandomReal[{0, 1}, {10, 4}]


How to quickly make a table where the ith row of tab1 follows by 2(i-1)+1th and 2*ith rows of tab2, and for each corresponding 3 rows, one adds the row {tab1[[i]][[1]],0,0,0}? The ugly way to do this is

Flatten[Table[{{tab1[[i]][[1]],0,0,0},tab1[[i]],tab2[[2*(i-1)+1]],tab2[[2*i]]},{i,1,Length[tab1],1}],1]

• are you sure you only wanted to give a single argument to Table and a symbolic i ? Commented Oct 22, 2023 at 18:21
• @userrandrand : thanks! I have fixed the code. Commented Oct 22, 2023 at 19:34
• Does Flatten[Riffle[{{#[[1]],0,0,0},#}&/@tab1,Partition[tab2,2]],1] pass your ugly test? I think it produces exactly the same output as your code. Test this carefully before you trust it.
– Bill
Commented Oct 22, 2023 at 20:35

You want pairs of items from your first list

{{#[[1]],0,0,0},#}&/@tab1


and pairs of items from your second list

Partition[tab2,2]


Alternate those pairs of pairs

Riffle[{{#[[1]],0,0,0},#}&/@tab1,Partition[tab2,2]]


and strip off the extra layer of {} introduced by the pairing

Flatten[Riffle[{{#[[1]],0,0,0},#}&/@tab1,Partition[tab2,2]],1]


I'd try something like this:

n1 = 5;
n2 = 2*n1;
n3 = n2 + 2*n1;
tab1 = ArrayReshape[Range[n1*4], {n1, 4}]; (* tab1 = RandomReal[{0, 1}, {n1, 4}]; *)
tab2 = ArrayReshape[100*Range[n2*4], {n2, 4}]; (*  tab2 = RandomReal[{0, 1}, {n2, 4}];*)
tab3 = PadRight[Take[tab1, All, 1], {n1, 4}]; (* Explicitly construct a third table to facilitate Riffle-ing *)

(* I made the tables non-random so that you can see what's going on. *)

Riffle[Riffle[tab2, tab1, {1, -2, 3}], tab3, {1, -2, 4}]