I'm new to Scala and am having trouble iterating through an array to assign values to a Matrix. My programming background is mostly Python, so I'm having difficulty seeing the functional way to do this task.
I've got an Array, val averages = Array(1,2,3,4,5,6,7,8,9), and I've got an empty 3x3 matrix, M, made with Scala library breeze. I need to take the values from the Array and put them into the matrix.
Normally, I would try something like:
var index = 0
for(i <- 0 until M.cols)
for(j <- 0 until M.rows)
M(i,j) = averages(index)
index += 1
This doesn't work, and results in a matrix simply filled with "1"s. I assume this is because Scala is evaluating M(i,j) = averages(index) before it gets to index += 1. I've experimented with different types of for loops for averages, but can't quite get the result I want:
1 2 3
4 5 6
7 8 9
I know that in Scala with the Random collection you can do this, and fill the matrix with random variables:
val r = new scala.util.Random(0)
for(i <- 0 until M.rows)
for(j <- 0 until M.cols)
M(i, j) = r.nextDouble()
But looking at the Scala documentation, Array doesn't have the .next method.
At any rate, even using .next is very iterative, and not a functional solution. Can anyone help me 1) Figure out the proper way to loop through averages and/or 2) Figure out a functional way to do this? Thanks!
val averages = Array(1,2,3,4,5,6,7,8,9).toIteratorNow it has anext.Matrix.create(3, 3, array)...