Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepend a column to a matrix?

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?

like image 852
nes1983 Avatar asked Aug 07 '09 13:08

nes1983


People also ask

How do you add a column to a matrix?

For adding a column to a Matrix in we use cbind() function. To know more about cbind() function simply type ? cbind() or help(cbind) in R. It will display documentation of cbind() function in R documentation as shown below.

How do you turn a column vector into a matrix?

To convert a vector into matrix, just need to use matrix function. We can also define the number of rows and columns, if required but if the number of values in the vector are not a multiple of the number of rows or columns then R will throw an error as it is not possible to create a matrix for that vector.

How do I add a column to a matrix in R?

The cbind() function adds additional columns to a matrix in R.


2 Answers

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.

like image 150
Janus Avatar answered Oct 17 '22 23:10

Janus


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

PrependColumn[vector_List, matrix_List] := 
  Transpose[Prepend[Transpose[matrix], vector]]
like image 44
dreeves Avatar answered Oct 17 '22 21:10

dreeves