Skip to content

Commit 26d2e97

Browse files
authored
Fix select_indices issue and add test (#302)
1 parent beca4cd commit 26d2e97

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

‎src/common/pullbacks.jl‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,12 @@ function select_indices(r::AbstractRange, ind::AbstractVector{<:Integer})
2626
checkbounds(r, ind)
2727
return first(r) .+ step(r) .* (ind .- 1)
2828
end
29+
# `Bool <: Integer`, so logical masks need to
30+
# be converted *before* the arithmetic above
31+
function select_indices(r::AbstractRange, ind::AbstractVector{Bool})
32+
checkbounds(r, ind)
33+
return select_indices(r, findall(ind))
34+
end
2935

3036
"""
3137
is_leading_index(ind, p::Int)

‎test/common/select_indices.jl‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using MatrixAlgebraKit
2+
using MatrixAlgebraKit: select_indices
3+
using Test
4+
5+
# `Bool <: Integer`, so logical masks used to hit the integer-index arithmetic in
6+
# `select_indices` and silently produce wrong indices (e.g. `[1, 0, 1, ...]`).
7+
@testset "select_indices" begin
8+
r = 1:6
9+
mask = [true, false, true, false, false, true]
10+
@test select_indices(r, mask) == [1, 3, 6]
11+
@test select_indices(r, view(mask, 1:6)) == [1, 3, 6]
12+
@test select_indices(r, falses(6)) == Int[]
13+
@test select_indices(r, [1, 3, 6]) == [1, 3, 6]
14+
@test select_indices(r, 2:4) == 2:4
15+
@test select_indices(r, :) == r
16+
@test select_indices(3:2:13, mask) == [3, 7, 13]
17+
@test_throws BoundsError select_indices(r, [true, false])
18+
end

0 commit comments

Comments
 (0)