Multiple selection from Julia array

In Julia, is there a way to get a vector containing multiple elements from a multidimensional array, similar to numpy extended indexing? For example, from this two-dimensional array:

genconv = reshape([6,9,7,1,4,2,3,2,0,9,10,8,7,8,5], 5, 3) genconv[[1,2,3],[2,3,1]] 

The result is a 3x3 array, not a vector: screenshot

+5
source share
3 answers

To get elements using col and row , one way is to use the sub2ind function:

getindex(genconv,sub2ind(size(genconv),[1,2,3],[2,3,1]))

EDIT

as already @ user3580870 commented

getindex(genconv,sub2ind(size(genconv),[1,2,3],[2,3,1])) is equal to genconv[sub2ind(size(genconv),[1,2,3],[2,3,1])]

what I got does not show a difference in performance between getindex syntax and syntax syntax.

+5
source

Julia 0.5 now supports indexing by CartesianIndex es arrays. A CartesianIndex is a special type of index that spans several dimensions:

 julia> genconv = reshape([6,9,7,1,4,2,3,2,0,9,10,8,7,8,5], 5, 3) 5Γ—3 Array{Int64,2}: 6 2 10 9 3 8 7 2 7 1 0 8 4 9 5 julia> genconv[CartesianIndex(2,3)] # == genconv[2,3] 8 

Interestingly, you can use CartesianIndex es vectors to specify this numpy-style streaming indexing:

 julia> genconv[[CartesianIndex(1,2),CartesianIndex(2,3),CartesianIndex(3,1)]] 3-element Array{Int64,1}: 2 8 7 

This is a rather verbose and scary look, but it can be combined with the new special syntax f.() For a very nice solution:

 julia> genconv[CartesianIndex.([1,2,3],[2,3,1])] 3-element Array{Int64,1}: 2 8 7 
+4
source

Another option is to simply process the data as a vector, rather than a multidimensional array:

 genconv = [6,9,7,1,4,2,3,2,0,9,10,8,7,8,5] genconv[ [10, 13] ] 
+2
source

Source: https://habr.com/ru/post/1236043/


All Articles