This is strongly related to the following Questions:
- Looking for a way to insert multiple elements into multiple positions simultaneously in a list
- Building matrices by attaching vectors (columns) and matrices
- What is the most efficient way to add rows and columns to a matrix?
I am looking for an efficient method to insert an array into an array. Let’s assume that both arrays have similar number of rows. Let’s further assume insertion is by column.
a = {{a1, b1, c1, d1, e1}, {a2, b2, c2, d2, e2}, {a3, b3, c3, d3, e3}}; (*example may be larger*)
b = {{x1, y1, z1}, {x2, y2, z2}, {x3, y3, z3}}; (*example may be larger*)
Q1: What is the fastest method to insert b into a at a position p. Let’s assume that both arrays have similar number of rows. Let’s further assume insertion is by column.
My current method is as follows:
insertarray[a_, b_, pos_] :=
FlattenAt[
Transpose@Insert[Transpose@a, b[[##]], pos ] & [Range[Length@a]],
Table[{i, pos}, {i, 1, Length@a}]];
which allows me to do
Q2: Some times I have to intersperse columns of b into a at multiple positions. How do I best extend insertarray so that:
insertarray[a,b,{1,2,5}]//MatrixForm