Search code examples
arraysloopsjuliadynamic-arrays

How can I implement 5 dimensional array in one for loop in julia?


function prealloc()
    situation=zeros(Int64,3^5,5);
    i=1;
    for north=0:2
        for south=0:2
            for east=0:2
                for west=0:2
                    for current=0:2
                        situation[i,:]=[north, south, east, west, current]
                        i+=1
                    end
                end
            end
        end
    end
    situation
end
prealloc()

How can I implement this code on one for loop or in only one loop how I use nested loops to do that


Solution

  • You could combine the for loops into one loop with multiple variables.

    function prealloc()
        situation=zeros(Int64,3^5,5);
        i=1;
        for north=0:2, south=0:2, east=0:2, west=0:2, current=0:2
            situation[i,:]=[north, south, east, west, current]
            i+=1
        end
        situation
    end