Reputation: 380
I'm new to Scala (Python background) and trying to implement a Quadtree for my sparse data and attempting to use Breeze
to do so (although if you have a better suggestion, I'm totally open to it).
My problem is this: I need to know how to update a matrix at (x,y) without recursing through simply i <- 0 until matrix.rows
because I don't have the values for all the rows and columns, I only have specific xs and ys. If this is unclear here's what I mean: In the breeze
documentation, you normally see something like this
val r = new scala.util.Random(100)
for(i <-0 until Matrix.rows)
for(j <- 0 until Matrix.cols)
Matrix(i,j) = r.nextInt
return Matrix
This is fine and dandy if I had a value for EVERY value in the matrix, but I don't. Instead what I'm working with is something like this.
val points: Array[Double] = Array(3.0, 5.0, 8.0)
val xs: Array[Double] = Array(2.0, 5.0, 6.0)
val ys: Array[Double] = Array(3.0, 4.0, 6.0)
where I want matrix(2,3) = 3.0
Where I know that my matrix should be a 6x6 matrix DenseMatrix[Double](6,6)
.
Assuming that I begin with a matrix of zeros (DenseMatrix.zeros(6,6)
) how can I insert my points
using my xs
and ys
rather than .rows
and .cols
?
I have tried this:
(where emptym
is a 6x6 matrix of zeros)
val matrix = for {
| x <- xs
| y <- ys
| p <- points
| } yield (emptym(x.toInt,y.toInt) = p)
which gives me all kinds of errors :/
I was thinking maybe I could do this with some kind of map
function, because I want to return a val for this but I'm new enough to scala that I cant quite figure out how to do this.
Please help me figure this out. Thanks! :)
Edit -- Ideally, I'm hoping for a more FP solution that doesn't have to loop through the matrix and update it. I'd like to create a new matrix. I'm thinking something like this, but can't get it to work:
val newMatrix = oldMatrix.map(xs, ys, points => oldMatirx(x,y) = point)
Upvotes: 0
Views: 575
Reputation: 215067
You can use the update method, where you can pass the row number, col number and the value to update a cell in the matrix:
val mat = DenseMatrix.zeros[Double](6,6)
for (i <- 0 until xs.length) {
mat.update(xs(i).toInt - 1, ys(i).toInt - 1, points(i))
}
Print the matrix out:
for (i <- 0 until mat.rows){
for(j <- 0 until mat.cols) {
print(mat(i, j) + " ")
}
println()
}
0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 3.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 5.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 8.0
Upvotes: 1