andrew
andrew

Reputation: 4089

Scala multidimensional array equivalent of np.ndarray.shape?

Is there a pithy way to get the shape of a multidimensional array in Scala? I'm thinking of something equivalent to the following using Numpy in Python:

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
a
>> array([[1, 2, 3],
       [4, 5, 6]])
a.shape
>> (2, 3)

Upvotes: 2

Views: 952

Answers (1)

user unknown
user unknown

Reputation: 36269

If you are sure, that all the inner Arrays are of the same size, you can do:

scala> val aaa = Array ( Array (1,2,3), Array (4,5,6))                        
aaa: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6))

scala> val aaaShape = (aaa.size, aaa(0).size)
aaaShape: (Int, Int) = (2,3)

but an Array of Arrays doesn't guarantee, that all inner Arrays are of the same size.

A method like a.shape seems over engineering, but you may write it yourself easily and then implement a check for even size of each subarray, if appropriate.

Upvotes: 2

Related Questions