How do you make an arbitrarily nested for loop?

Say you have an array of ranges rngs = [10:-1:0, 10:-4:2, 10:-3:1].
How would you make a nested loop equivalent to

inds = zeros(length(rngs))
for inds[1] in rngs[1], inds[2] in rngs[2], inds[3] in rngs[3]

But for an arbitrary array of ranges?

Use a tuple of ranges with CartesianIndices:

rngs = (10:-1:0, 10:-4:2, 10:-3:1)
for i in CartesianIndices(rngs)
    inds = Tuple(i)
    @show inds
end

(You ideally want a tuple and not an array for this sort of thing, because you want the length — i.e., the number of nested loops — to be known to the compiler.)

4 Likes

Another way would be to loop over this iterator

Iterators.product(rngs...)
1 Like