Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`map` equivalent to 2d list comprehension

In 1d, I can use either of these:

[i for i in 1:5] 

or

map(1:5) do i 
    i
end

both produce

[1,2,3,4,5]

Is there a way to use map in higher dimensions? e.g. to replicate

[x + y for x in 1:5,y in 10:13] 

which produces

5×4 Array{Int64,2}:
 11  12  13  14
 12  13  14  15
 13  14  15  16
 14  15  16  17
 15  16  17  18
like image 223
Alec Avatar asked Dec 13 '22 07:12

Alec


1 Answers

You can do this:

julia> map(Iterators.product(1:3, 10:15)) do (x,y)
         x+y
       end
3×6 Array{Int64,2}:
 11  12  13  14  15  16
 12  13  14  15  16  17
 13  14  15  16  17  18

The comprehension you wrote is I think just collect(x+y for (x,y) in Iterators.product(1:5, 10:13)), . Note the brackets (x,y), as the do function gets a tuple. Unlike x,y when it gets two arguments:

julia> map(1:3, 11:13) do x,y
         x+y
       end
3-element Array{Int64,1}:
 12
 14
 16
like image 168
mcabbott Avatar answered Dec 26 '22 19:12

mcabbott