DornerA
DornerA

Reputation: 135

Using a find() function with two vectors

I am using the Julia programming language, and I know that you can use the find function in the following way:

a = [ 1 2 3 4 3 5 3 6 7 8 9 3 ]
find(a .== 3)

It will return: 3, 5, 7, 12

Simple enough.

However, my question is, what if we want to replace the 3 in the above code to be a vector.

For example:

a = [1 2 3 4 5 6 7]
b = [1 9 5 8]

The following syntax has not worked for me, but it conveys my idea. How would I do the following correctly?:

find (a .== b)

If we want it to return 1, 3?

I know the matching function in R does this well, but I have a very large dataset, and R has not been handling it well.

Upvotes: 3

Views: 171

Answers (2)

DNF
DNF

Reputation: 12664

You can do this:

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

or since you wanted 1, 3:

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

I also suggest that you use

a = [1, 2, 3, 4, 5, 6, 7]
b = [1, 9, 5, 8]

instead of the version without commas, since column operations are more efficient than row operations in Julia.

Furthermore, it is more efficient to write find(x->x==3, a) than find(a.==3) since the latter will first create a full boolean vector and then search that, while the former will simply iterate through each element of a and perform the comparison.

Edit: If you are curious about the anonymous function notation, you should look up help for the find function. The point is that

find(f, a)

applies the function f to each element of a before while it is evaluating the find part.

Upvotes: 3

user4651282
user4651282

Reputation:

Another way - use function findin/2 :

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

julia> findin(a,b)
2-element Array{Int64,1}:
 1
 5

Upvotes: 7

Related Questions