Julia Language for Loops Multidimensional iteration

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Julia Language Question?