41

28

Say I have a matrix m and a vector v.

```
v = {a[1], a[2], a[3], a[4]};
m={{a[1,1],a[1,2],a[1,3],a[1,4]},
{a[2,1],a[2,2],a[2,3],a[2,4]},
{a[3,1],a[3,2],a[3,3],a[3,4]},
{a[4,1],a[4,2],a[4,3],a[4,4]}};
```

What is the most efficient way to add v to the rows of m to create...

```
mrow={{a[1],a[2],a[3],a[4]},
{a[1,1],a[1,2],a[1,3],a[1,4]},
{a[2,1],a[2,2],a[2,3],a[2,4]},
{a[3,1],a[3,2],a[3,3],a[3,4]},
{a[4,1],a[4,2],a[4,3],a[4,4]}}
```

Likewise, what is the most efficient way to add v to the columns of m to create...

```
mcol={{a[1],a[1,1],a[1,2],a[1,3],a[1,4]},
{a[2],a[2,1],a[2,2],a[2,3],a[2,4]},
{a[3],a[3,1],a[3,2],a[3,3],a[3,4]},
{a[4],a[4,1],a[4,2],a[4,3],a[4,4]}};
```

**EDIT**: I've tested some of the suggestions for adding a column with a large matrix and was somewhat surprised by the results.

```
m = RandomVariate[NormalDistribution[], {1000, 1000}];
v = RandomVariate[NormalDistribution[], 1000];
In[37]:= AbsoluteTiming[Do[MapThread[Prepend, {m, v}], {100}];]
Out[37]= {1.809623, Null}
In[38]:= AbsoluteTiming[Do[Transpose[Prepend[Transpose[m], v]], {100}];]
Out[38]= {2.449231, Null}
In[39]:= AbsoluteTiming[Do[Transpose[Join[Transpose[m], {v}]], {100}];]
Out[39]= {2.271853, Null}
```

@Sasha The above timings are correct for the addition of a column to a matrix (I confirmed them), but in the case of a row, I am getting rather different results:

`AbsoluteTiming[Do[Join[m, {v}], {10^3}]] Out[231]={0.619549, Null}`

`AbsoluteTiming[Do[Transpose[MapThread[Append, {Transpose[m], v}]], {10^3}]] Out[233]={8.1198, Null}`

`AbsoluteTiming[Do[ArrayFlatten[{{m}, {{v}}}], {10^3}]] Out[232]={49.0553, Null}`

I think this might be useful for new users who might just copy the code, as they are still not aware what is quick/slow when it comes to working with

`Lists`

– ThunderBiggi – 2017-04-04T09:30:22.1933

`Join`

is faster than`ArrayFlatten`

(for these examples anyway). – Mike Honeychurch – 2012-01-18T22:54:08.123@MikeHoneychurch Thanks for reminding me of

`Join`

(+1). In my timings, there is no measurable difference, but I agree`Join`

feels more natural than`ArrayFlatten`

. – Sasha – 2012-01-19T05:12:30.490