Operations with CartesianIndex

Viewed 282

I'd like to know how can I operate with CartesianIndex. For example I have array

julia> A = rand(1:5, 10, 2)
10×2 Array{Int64,2}:
 2 5
 1 1
 4 5
 4 1
 2 1
 4 1
 2 4
 1 5
 2 5
 4 4

and I want to save all numbers which stay near (in pair) with number 1. I can use c=findall(x->x==1, A), but I will have a cartensian indexes of "1". There is function x=getindex.(c, [1 2]) it makes an array which I can change, but I don't know how to convert it back to CartesianIndex. And I think that must be a better way to do this.

1 Answers
A[view(A.==1,:,[2,1])]

This literally returns "all numbers which stay in pair with number 1".

The order of returned numbers is columnar. If you want to return it by rows:

 A'[view(A.==1,:,[2,1])']

Example:

julia> A = rand(1:5, 10, 2)
10×2 Array{Int64,2}:
 1  4
 3  3
 1  3
 3  3
 5  1
 1  5
 2  1
 3  3
 1  3
 2  3

julia> A'[view(A.==1,:,[2,1])']
6-element Array{Int64,1}:
 4
 3
 5
 5
 2
 3

If you rather want full rows than use filter!:

julia> filter!((x)->(1 in x), collect(eachrow(A)))
6-element Array{SubArray{Int64,1,Array{Int64,2},Tuple{Int64,Base.Slice{Base.OneTo{Int64}}},true},1}:
 [1, 4]
 [1, 3]
 [5, 1]
 [1, 5]
 [2, 1]
 [1, 3]
Related