小白请问julia如何实现matlab中的ismember函数?

刚从matlab转julia,现在希望比较两个向量是否存在相同元素,并输出元素位置,请问在julia中应该如何实现。

findall?

julia> a = [10, 20, 30];

julia> b = [20, 30, 40, 50];

julia> Ra = findall(x->x in b, a)
2-element Array{Int64,1}:
 2
 3

julia> a[Ra]
2-element Array{Int64,1}:
 20
 30

julia> Rb = findall(x->x in a, b)
2-element Array{Int64,1}:
 1
 2

julia> b[Rb]
2-element Array{Int64,1}:
 20
 30

或者利用 Julia的广播,以及 BitArray 可以作为下标的特性:

julia> Ra = vec(Bool.((sum(a .== b', dims=2))))
3-element BitArray{1}:
 0
 1
 1

julia> Ra = any.(eachrow(a .== b'))
3-element BitArray{1}:
 0
 1
 1

julia> a[Ra]
2-element Array{Int64,1}:
 20
 30

julia> Rb = vec(Bool.((sum(a .== b', dims=1))))
4-element BitArray{1}:
 1
 1
 0
 0

julia> Rb = any.(eachcol(a .== b'))
4-element BitArray{1}:
 1
 1
 0
 0

julia> b[Rb]
2-element Array{Int64,1}:
 20
 30

不过 a .== b' 会占用比较大的临时内存,所以性能上是会有差距的

1 个赞

有个 indexin, 不知道是不是你想要的:

help?> indexin
search: indexin IndexLinear IndexCartesian InvalidStateException IndexStyle setindex! getindex findnext lastindex eachindex checkindex

  indexin(a, b)

  Return an array containing the first index in b for each value in a that is a member of b. The output array contains nothing wherever a is not a
  member of b.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];
  
  julia> b = ['a', 'b', 'c'];
  
  julia> indexin(a, b)
  6-element Array{Union{Nothing, Int64},1}:
   1
   2
   3
   2
    nothing
   1
  
  julia> indexin(b, a)
  3-element Array{Union{Nothing, Int64},1}:
   1
   2
   3
1 个赞

又发现一个新函数hhh,我发现也还是有一些速度上的差异的:

julia> a = rand(1:1000, 1000);

julia> b = rand(1:1000, 1000);

julia> @btime filter(x->!isnothing(x), indexin($a, $b));
  32.118 μs (15 allocations: 41.84 KiB)

julia> @btime findall(x->x in $b, $a);
  195.065 μs (16 allocations: 16.58 KiB)

julia> a = rand(1:1000, 1000, 1000);

julia> b = rand(1:1000, 1000, 1000);

julia> @btime filter(x->!isnothing(x), indexin($a, $b));
  23.508 ms (22 allocations: 32.56 MiB)

julia> @btime findall(x->x in $b, $a);
  322.982 ms (26 allocations: 17.00 MiB)