4

Is there a single function in Julia that will give you the total number of elements in an array-of-arrays (or 'jagged array')?

Here's what I mean:

my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ] 

I'm looking for a function such that desired_function(my_array_of_arrays) will return 6

And if not, what's the quickest way to do this in Julia?

Thanks in advance!

Conor
  • 691
  • 5
  • 14

2 Answers2

5

One way to do it without additional dependencies would be to use sum:

julia> my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ] 
3-element Array{Array{Int64,1},1}:
 [1, 5]
 [6]
 [10, 10, 11]

julia> sum(length, my_array_of_arrays)
6


However, if you want to work more intensively with ragged arrays, you might be better off using specialized packages, such as ArraysOfArrays.jl.

François Févotte
  • 19,520
  • 4
  • 51
  • 74
4

sum(length, x) suggested by @MattB is a more elegant answer and it deserves being here so others can find it.

Testing:

julia> my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ]
3-element Array{Array{Int64,1},1}:
 [1, 5]
 [6]
 [10, 10, 11]

julia> sum(length, my_array_of_arrays)
6

Note that the performance of both methods mapreduce(length, +, x) and sum(length, x) is identical since both do not materialize the data.

Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62
  • Thanks for pointing this out, I see that the original poster of the 'accepted answer' has edited their answer to reflect this. – Conor May 31 '20 at 11:32