logankilpatrick
logankilpatrick

Reputation: 14501

How to create two nested for loops in a single line in Julia

I have seen it a few times where someone has a situation where they want to put two for loops on the same line nested in one another.

Just to confirm, is this possible in Julia and if so what does it look like? Thanks!

Upvotes: 6

Views: 2736

Answers (1)

David Sainez
David Sainez

Reputation: 6956

Correct, Julia allows you to tersely express nested for loops.

As an example, consider filling in a 3x3 matrix in column order:

julia> xs = zeros(3,3)
3×3 Array{Float64,2}:
 0.0  0.0  0.0
 0.0  0.0  0.0
 0.0  0.0  0.0

julia> let a = 1
           for j in 1:3, i in 1:3
               xs[i,j] = a
               a += 1
           end
       end

julia> xs
3×3 Array{Float64,2}:
 1.0  4.0  7.0
 2.0  5.0  8.0
 3.0  6.0  9.0

The above loop is equivalent to this more verbose version:

julia> let a = 1
           for j in 1:3
               for i in 1:3
                   xs[i,j] = a
                   a += 1
               end
           end
       end

This syntax is even supported for higher dimensions(!):

julia> for k in 1:3, j in 1:3, i in 1:3
           @show (i, j, k)
       end

Upvotes: 14

Related Questions