Julia Language Multidimensional iteration


Example

In Julia, a for loop can contain a comma (,) to specify iterating over multiple dimensions. This acts similarly to nesting a loop within another, but can be more compact. For instance, the below function generates elements of the Cartesian product of two iterables:

function cartesian(xs, ys)
    for x in xs, y in ys
        produce(x, y)
    end
end

Usage:

julia> collect(@task cartesian(1:2, 1:4))
8-element Array{Tuple{Int64,Int64},1}:
 (1,1)
 (1,2)
 (1,3)
 (1,4)
 (2,1)
 (2,2)
 (2,3)
 (2,4)

However, indexing over arrays of any dimension should be done with eachindex, not with a multidimensional loop (if possible):

s = zero(eltype(A))
for ind in eachindex(A)
    s += A[ind]
end