If I have an Array[Array[Double]]
in Scala, is there an idomatic way to map over the second axis?
For instance, consider the following matrix:
val M : Array[Array[Double]] = Array(Array(1d,2d),Array(3d,4d),Array(5d,6d))
To normalize the rows I simply run:
M.map(x=>x.map(_/x.sum))
However, the normalize the columns it seems like I must execute:
M.transpose.map(x=>x.map(_/x.sum)).transpose
This is workable, but it becomes extremely tedious if I have more than two indices. In generally if I want to map over the last axis of a bunch of nested Array
, i.e., Array[Array[...Array[Double]...]]
, then I need to bubble the last axis to the front via map and transpose, then map over it, then bubble it back to the back.