Skip to content

Commit

Permalink
Change indexin() to return first rather than last matching index (Jul…
Browse files Browse the repository at this point in the history
…iaLang#25998)

That's more natural, and consistent with MATLAB's ismember() and R's match().
  • Loading branch information
nalimilan committed Feb 14, 2018
1 parent 4c4aaaf commit 9a239ec
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 9 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,8 @@ This section lists changes that do not have deprecation warnings.
* The `fieldnames` and `propertynames` functions now return a tuple rather than
an array ([#25725]).

* `indexin` now returns the first rather than the last matching index ([#25998]).

Library improvements
--------------------

Expand Down Expand Up @@ -1300,3 +1302,4 @@ Command-line option changes
[#25655]: https://github.com/JuliaLang/julia/issues/25655
[#25725]: https://github.com/JuliaLang/julia/issues/25725
[#25745]: https://github.com/JuliaLang/julia/issues/25745
[#25998]: https://github.com/JuliaLang/julia/issues/25998
15 changes: 9 additions & 6 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2139,7 +2139,7 @@ argmin(a) = findmin(a)[2]
"""
indexin(a, b)
Return an array containing the highest index in `b` for
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`.
Expand All @@ -2160,15 +2160,18 @@ julia> indexin(a, b)
julia> indexin(b, a)
3-element Array{Union{Nothing, Int64},1}:
6
4
1
2
3
```
"""
function indexin(a, b::AbstractArray)
indexes = keys(b)
bdict = Dict(zip(b, indexes))
return Union{eltype(indexes), Nothing}[
inds = keys(b)
bdict = Dict{eltype(b),eltype(inds)}()
for (val, ind) in zip(b, inds)
get!(bdict, val, ind)
end
return Union{eltype(inds), Nothing}[
get(bdict, i, nothing) for i in a
]
end
Expand Down
6 changes: 3 additions & 3 deletions test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1415,9 +1415,9 @@ end
# PR #8622 and general indexin tests
@test indexin([1,3,5,7], [5,4,3]) == [nothing,3,1,nothing]
@test indexin([1 3; 5 7], [5 4; 3 2]) == [nothing CartesianIndex(2, 1); CartesianIndex(1, 1) nothing]
@test indexin((2 * x + 1 for x in 0:3), [5,4,3,5,6]) == [nothing,3,4,nothing]
@test indexin(6, [1,3,6,6,2]) == fill(4, ())
@test indexin([6], [1,3,6,6,2]) == [4]
@test indexin((2 * x + 1 for x in 0:3), [5,4,3,5,6]) == [nothing,3,1,nothing]
@test indexin(6, [1,3,6,6,2]) == fill(3, ())
@test indexin([6], [1,3,6,6,2]) == [3]
@test indexin([3], 2:5) == [2]
@test indexin([3.0], 2:5) == [2]

Expand Down

0 comments on commit 9a239ec

Please sign in to comment.