I have a 2D Array, say a 3x3 Matrix, and want to multiply all elements with a given value. This is what I have so far:
val m = Array(
Array(1,2,3),
Array(4,5,6),
Array(7,8,9)
)
val value = 3
for ( i <- m.indices) yield m(i).map(x => x*value)
//Result:
//IndexedSeq[Array[Int]] = Vector(Array(3, 6, 9), Array(12, 15, 18), Array(21, 24, 27))
Problem is I have an IndexedSeq[Array[Int]]
now but I need this to be an Array[Array[Int]]
just like val m
.
I know that for example for (i <- Array(1, 2, 3)) yield i
results in an Array[Int]
but I can't figure out how to put this all together.
Just appending .toArray
doesn't work also
CodePudding user response:
If you want to create new Array
instances (copy):
val m = Array(
Array(1,2,3),
Array(4,5,6),
Array(7,8,9)
)
val value = 3
val newM = m.map{ array => array.map{x => x * value}}
Or, if you want to modify the original arrays "in-place":
val m = Array(
Array(1,2,3),
Array(4,5,6),
Array(7,8,9)
)
val value = 3
for (arr <- m; j <- arr.indices) {
arr(j) *= value
}