Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 417
logankilpatrick Avatar asked Dec 29 '19 05:12

logankilpatrick


1 Answers

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
like image 186
David Varela Avatar answered Sep 25 '22 14:09

David Varela