1

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.

suish
  • 3,253
  • 1
  • 15
  • 34
Paul
  • 503
  • 4
  • 15
  • why don't you use the breeze [library](https://github.com/scalanlp/breeze) that allows you to deal with all kind of matrix calculation? – proximator Jul 29 '18 at 19:59
  • @proximator in production I probably would, but with regards to the current question it doesn't give me any insight into the workings of Scala or functional programming tricks. – Paul Aug 01 '18 at 17:37

0 Answers0