views:

179

answers:

3

Ok, imagine I have this Matrix: {{1,2},{2,3}}, and I'd rather have {{4,1,2},{5,2,3}}. That is, I prepended a column to the matrix. Is there an easy way to do it?

My best propsel is this:

PrependColumn[vector_List, matrix_List] := Outer[Prepend[#1, #2] &, matrix, vector, 1]

But it obfuscaates the code and constantly requires loading more and more code. Isn't this built in somehow?

+2  A: 

I think the least obscure is the following way of doing this is:

PrependColumn[vector_List, matrix_List] := MapThread[Prepend, {matrix, vector}];

In general, MapThread is the function that you'll use most often for tasks like this one (I use it all the time when adding labels to arrays before formating them nicely with Grid), and it can make things a lot clearer and more concise to use Prepend instead of the equivalent Prepend[#1, #2]&.

Pillsy
+2  A: 

I believe the most common way is to transpose, prepend, and transpose again:

PrependColumn[vector_List, matrix_List] := 
  Transpose[Prepend[Transpose[matrix], vector]]
dreeves
+2  A: 

Since ArrayFlatten was introduced in Mathematica 6 the least obfuscated solution must be

matrix = {{1, 2}, {2, 3}}
vector = {{4}, {5}}

ArrayFlatten@{{vector, matrix}}

A nice trick is that replacing any matrix block with 0 gives you a zero block of the right size.

Janus