Julia: find the row in the matrix

Using Julia, I would like to determine if a row is in the matrix and (if applicable) where the row is in the matrix. For example, in Matlab, this can be done with ismember:

a = [1 2 3];
B = [3 1 2; 2 1 3; 1 2 3; 2 3 1]
B =

 3     1     2
 2     1     3
 1     2     3
 2     3     1

ismember(B, a, 'rows')
ans =

 0
 0
 1
 0

This shows what ais on line 3 of B. Is there a similar function for this in Julia?

+4
source share
4 answers

Another template uses array understanding:

julia> Bool[ a == B[i,:] for i=1:size(B,1) ]
4-element Array{Bool,1}:
false
false
true
false

julia> Int[ a == B[i,:] for i=1:size(B,1) ]
4-element Array{Int64,1}:
0
0
1
0
+4
source

You can also use broadcast array transmission by simply checking equality ( .==) without using concepts:

all(B .== a, 2)

What gives you:

4x1 BitArray{2}:
 false
 false
  true
 false

Then you can use find in this array to get row indices:

find(all(B .== a, 2))

And you will get:

1-element Array{Int64,1}:
 3
+6

Julia , , .

a = [1 2 3];
B = [3 1 2; 2 1 3; 1 2 3; 2 3 1]
ismember(mat, x, dims) = mapslices(elem -> elem == vec(x), mat, dims)
ismember(B, a, 2)  # Returns booleans instead of ints
+4

:

matchrow(a,B) = findfirst(i->all(j->a[j] == B[i,j],1:size(B,2)),1:size(B,1))

returns 0when there is no corresponding line or the number of the first line, if any.

matchrow(a,B)

3

should be as quick and fairly simple as possible.

+1
source

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


All Articles