3

I've a vector and a matrix:

1
1

0 0
0 0

I want to prepend the vector to matrix to produce :

1 0 0
1 0 0

I have so far :

val dv = DenseVector(1.0,1.0);
val dm = DenseMatrix.zeros[Double](2,2)

Reading the API : http://www.scalanlp.org/api/breeze/#breeze.linalg.DenseMatrix and both these docs : https://github.com/scalanlp/breeze/wiki/Quickstart https://github.com/scalanlp/breeze/wiki/Linear-Algebra-Cheat-Sheet

But this operation does not appear to be available ?

Is there a method/function to prepend a vector of ones to a Matrix ?

blue-sky
  • 51,962
  • 152
  • 427
  • 752

2 Answers2

4

Another option here. Firstly convert the DenseVector to a 2X1 matrix and then use the DenseMatrix.horzcat() method:

val newMat = DenseMatrix.horzcat(new DenseMatrix(2,1,dv.toArray), dm)

# breeze.linalg.DenseMatrix[Double] = 1.0  0.0  0.0  
#                                     1.0  0.0  0.0

newMat.rows
# 2
newMat.cols
# 3
Psidom
  • 209,562
  • 33
  • 339
  • 356
2

You can make a function to create your dense matrix with a column of ones prepended:

def prependOnesColumn[V](original: DenseMatrix[V]): DenseMatrix[V] = {
  val ones = DenseMatrix.ones(original.rows, 1)
  val dataWithOnes = ones.data ++ original.data
  DenseMatrix.create(original.rows, original.cols + 1, dataWithOnes)
}
Atreys
  • 3,741
  • 1
  • 17
  • 27
  • 1
    Psidom's answer looks like the idiomatic way of concatenating any number of matrices with breeze's library. – Atreys Dec 12 '16 at 15:52