-1

i have a collection of Vectors as

var coefficentsList = new MutableList[Vector]

I want to sum each element of the individual vector to each column of other vectors such. eg The coefficentsList will have the following vectors:

v1 = [0.2, 0.4, 0.1]
v2 = [0.4, 0.5, 0.1]
v3 = [0, 0, 0.3]

So I'd want the resultant vector like

V = [0.6, 0.9, 0.5]

Now to do this, i came across the breeze vectors here and here so i wrote the following code :

coefficentsList.toArray.map{
  Vector(_).reduce(_ + _)
}

but its giving me a type mismatch exception : found Array[Double], required : String

Is there any other way to do this as I'm stumped with this

Community
  • 1
  • 1
hbabbar
  • 947
  • 4
  • 15
  • 33
  • a `Vector` needs a type parameter so first, fix you type errors. Also, why did you need to use `toArray` ? Use `map` directly on your `MutableList` no ? – alifirat May 26 '16 at 07:56
  • 1
    @alifirat This can be `scala.collection.immutable.Vector`, `breeze.linalg.Vector` or `o.a.s.mllib.linalg.Vector` - it is not even clear from the context. – zero323 May 26 '16 at 08:01
  • @zero323 It is indeed o.a.s.mllib.linalg.Vector – hbabbar May 28 '16 at 14:27

1 Answers1

1

zip achieves right what you need

val coefficientsList = List(
  Vector(0.2, 0.4, 0.1),
  Vector(0.4, 0.5, 0.1),
  Vector(0.0, 0.0, 0.3)
)

val result = coefficientsList.reduceLeft { (acc, vec) =>
  acc zip vec map {
    case (a, b) => a + b
  }
}
// result: scala.collection.immutable.Vector[Double] = Vector(0.6, 0.9, 0.5)
Sergey
  • 2,880
  • 3
  • 19
  • 29