Larry
Larry

Reputation: 31

How to find locations of multiple elements in an array in Julia

Here is my code in Julia. I want to find locations of elements of array b in array a.

a = [2,4,1,3]
b = [1,4]
c=[]
for i in 1:length(b)
    push!(c, findfirst(isequal(b[i]), a));
end
println(c)

The result is [3, 2]. It's correct. But I believe there should be a more Julian (efficient) approach. I tried

julia> findall(x -> x == b, a)
0-element Array{Int64,1}

It's wrong. Then

julia> findall(x -> x == .b, a)
ERROR: syntax: invalid identifier name "."

or

julia> findall(x -> x .== b, a)
ERROR: TypeError: non-boolean (BitArray{1}) used in boolean context

The following result is wrong!

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

I think it considered 'b' as a set and ignored the sequence of elements in 'b'. I want the correct sequence [3,2]. Can anyone help me? Thanks.

Upvotes: 3

Views: 2269

Answers (2)

DNF
DNF

Reputation: 12654

indexin is probably the right solution, but what you were trying to do is probably

julia> findfirst.(.==(b), (a,))
2-element Array{Int64,1}:
 3
 2

The difference from indexin is that this will return an Array{Int64,1} if all elements are found, while indexin returns an Array{Union{Nothing, Int64},1} either way.

Upvotes: 4

fredrikekre
fredrikekre

Reputation: 10984

You can use indexin:

julia> a = [2,4,1,3]; b = [1,4];

julia> indexin(b, a)
2-element Array{Union{Nothing, Int64},1}:
 3
 2

However, don't be afraid of for-loops as in your first example, they are very readable and often as efficient (if not more) as built-in methods like indexin.

Upvotes: 7

Related Questions