Search code examples
julianested-for-loop

for loop vectors of vector in julia


  • first question

Suppose

b=[  [1,[2,3,4]], [4,[-2,1,0]]  ]

for i in 1:length(b)
   for a in b[i][2]
     print(a)
   end
end

I am getting 2 3 4 -2 1 0

instead of [2,3,4] ; [-2,1,0]

  • Second question

Why the following code is giving error [a for a in b[i][2] for i in 1:length(b)]

UndefVarError: i not defined


Solution

  • For the first question,

    b=[  [1,[2,3,4]], [4,[-2,1,0]]  ]
    
    for i in 1:length(b)
       for a in b[i][2]
         print(a)
       end
    end
    

    you are iterating over b[i][2] in the inner loop, so you get elements from [2,3,4] and [-2,1,0] as expected. You should println(b[i][2]), instead, and remove inner loop.

    A better loop would be:

    for (i,j) in b
        println(j)
    end
    

    For the second question,

    [a for a in b[i][2] for i in 1:length(b)]
    

    The order of the loops is reversed because the a loop depends on the i loop. You can fix it in either of two ways,

    [a for i in 1:length(b) for a in b[i][2]]
    # OR
    [[a for a in b[i][2]] for i in 1:length(b)]
    

    If you want the same answer as the first question but using array comprehension, this will do it:

    [j for (i,j) in b]