7

5

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
```

1"Insertion" is not very well defined as shown unless a and b both have the same length. If this is the case, you should tell everyone that constraint. – VF1 – 2014-03-21T15:14:24.073

@VF1 a and b both have the same number of column elements... but yes, it would be better to be explicit whether the insertion is by row or column (esp. with square matrices) – rm -rf – 2014-03-21T15:16:04.273

Edited for clarity. Added constraint insertion is by column. – Pam – 2014-03-21T15:17:10.163