【发布时间】:2015-05-29 20:27:44
【问题描述】:
下面的代码生成一个 0-1 矩阵,改变每一奇数行并组成一个新矩阵。我想使用foldLeft 连接向量,但得到Not all matrices have the same number of columns,可能是因为foldLeft 的零(或单位)元素是一个未知大小的空向量。
import breeze.linalg._
import breeze.stats.distributions._
object ZeroOneMatrix {
def main(args: Array[String]) {
val n = 4
val m = DenseMatrix.rand[Int](n, n, rand = Rand.randInt(2))
println(m)
// vs is of type Vector[DenseVector[Int]]
val vs = for (r <- 0 until n)
yield {
if (r % 2 == 1)
m(r, ::).t map (e => (e + 1) % 2)
else m(r, ::).t
}
println(vs)
// compose matrix back from the list of vectors vs
val f = (vs foldLeft DenseVector[Int]().asDenseMatrix)(
(mat, v) => DenseMatrix.vertcat(v.asDenseMatrix, mat))
println(f)
}
}
如何解决?还有为什么在不进行转接的情况下不能在m(r, ::) 上调用map?理想情况下,我会将所选向量映射到新向量,然后使用DenseMatrix.horzcat 构建矩阵。
不对整个矩阵使用map函数的原因是某些行不会被改变。
【问题讨论】:
标签: scala scala-breeze