How to prepend a column to a matrix?

2019-01-17 23:03发布

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 proposal is this:

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

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

4条回答
smile是对你的礼貌
2楼-- · 2019-01-17 23:22

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-17 23:24

THE... ABSOLUTELY.. BY FAR... FASTEST method to append or prepend a column from my tests of various methods on array RandomReal[100,{10^8,5}] (kids, don't try this at home... if your machine isn't built for speed and memory, operations on an array this size are guaranteed to hang your computer) ...is this: Append[tmp\[Transpose], Range@Length@tmp]\[Transpose]. Replace Append with Prepend at will.

The next fastest thing is this: Table[tmp[[n]]~Join~{n}, {n, Length@tmp}] - almost twice as slow.

查看更多
Fickle 薄情
4楼-- · 2019-01-17 23:37

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

PrependColumn[vector_List, matrix_List] := 
  Transpose[Prepend[Transpose[matrix], vector]]
查看更多
Bombasti
5楼-- · 2019-01-17 23:46

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]&.

查看更多
登录 后发表回答