coolsv
coolsv

Reputation: 781

How to find the length of each element of a multidimensional array in Julia?

Suppose we have a n-element Array{Array{Array{Int64,1},1},1} in Julia, listed below:

1) Element 1: 1-element Array{Array{Int64,1},1}: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 . 141, 142, 143, 144, 145, 146, 147, 148, 149, 150]

2) Element 2: 2-element Array{Array{Int64,1},1}: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 . 41, 42, 43, 44, 45, 46, 47, 48, 49, 50] [51, 52, 53, 54, 55, 56, 57, 58, 59, 60 . 141, 142, 143, 144, 145, 146, 147, 148, 149, 150]

and so on.

Actually, each element represents the connected components of several undirected graphs. Is there a command or a simple way to obtain the length of each deepest array (the number of connected components)? That is:

1) 150

2) 50 and 100

and so on.

Thank you!!

Upvotes: 0

Views: 240

Answers (1)

phipsgabler
phipsgabler

Reputation: 20980

Given

a = [[rand(3), rand(4)], [rand(5)]]

the version you already commented would be

julia> map(x -> length.(x), a)
2-element Array{Array{Int64,1},1}:
 [3, 4]
 [5]

Alternatively, the following in my opinion would be more readable:

julia> [[length(x) for x in y] for y in a]
2-element Array{Array{Int64,1},1}:
 [3, 4]
 [5]

But @juliohm is right, there might be better data structures than deeply nested arrays. Maybe have a look at LightGraphs.jl, if you're dealing with graph problems.

Upvotes: 2

Related Questions