Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to iterate over an array of arrays?

Tags:

julia

Let x::Vector{Vector{T}}. What is the best way to iterate over all the elements of each inner vector (that is, all elements of type T)? The best I can come up with is a double iteration using the single-line notation, ie:

for n in eachindex(x), m in eachindex(x[n])
    x[n][m]
end

but I'm wondering if there is a single iterator, perhaps in the Iterators package, designed specifically for this purpose, e.g. for i in some_iterator(x) ; x[i] ; end.

More generally, what about iterating over the inner-most elements of any array of arrays (that is, arrays of any dimension)?

like image 704
Colin T Bowers Avatar asked Jun 18 '16 23:06

Colin T Bowers


1 Answers

Your way

for n in eachindex(x), m in eachindex(x[n])
    x[n][m]
end

is pretty fast. If you want best speed, use

for n in eachindex(x)
    y = x[n]
    for m in eachindex(y)
        y[m]
    end
end

which avoids dereferencing twice (the first dereference is hard to optimize out because arrays are mutable, and so getindex isn't pure). Alternatively, if you don't need m and n, you could just use

for y in x, for z in y
    z
end

which is also fast.

Note that column-major storage is irrelevant, since all arrays here are one-dimensional.

To answer your general question:

  • If the number of dimensions is a compile-time constant, see Base.Cartesian
  • If the number of dimensions is not a compile-time constant, use recursion

And finally, as Dan Getz mentioned in a comment:

using Iterators
for z in chain(x...)
    z
end

also works. This however has a bit of a performance penalty.

like image 119
Fengyang Wang Avatar answered Sep 22 '22 04:09

Fengyang Wang