Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inplace mask of vector #39470

Closed
MasonProtter opened this issue Jan 31, 2021 · 2 comments
Closed

Inplace mask of vector #39470

MasonProtter opened this issue Jan 31, 2021 · 2 comments
Labels
arrays [a, r, r, a, y, s]

Comments

@MasonProtter
Copy link
Contributor

MasonProtter commented Jan 31, 2021

It was recently asked on Slack if there is an inplace equivalent of my_vector = my_vector[my_mask], where we assume that the user already needs the mask and does not want to essentially recompute it with filter!. I took a glance at the implementation of filter! in Base and saw that it could be easily adapted to this use-case:

function mask!(a::AbstractVector, m::AbstractVector{Bool})
    j = firstindex(a)
    for i in eachindex(a, m)
        @inbounds begin
            ai = a[i]
            mi = m[i]
            a[j] = ai
        end
        j = ifelse(mi, nextind(a, j), j)
    end
    j > lastindex(a) && return a
    if a isa Vector
        resize!(a, j-1)
        sizehint!(a, j-1)
    else
        deleteat!(a, j:lastindex(a))
    end
    return a
end

julia> let a = [:a, :b, :c], m = [true, false, true]
           mask!(a, m)
       end
2-element Vector{Symbol}:
 :a
 :c

Is this something that would be worth putting in Base? If so, I can whip up a PR, but don't want to waste my time if it's something that's already been discussed. I tried searching around but didn't find anything, but perhaps I missed a discussion.

@rfourquet
Copy link
Member

This seems quite related to the keepat! proposal at #36229, except this takes a list of indices instead of a mask.

@laborg
Copy link
Contributor

laborg commented Feb 6, 2022

This is fixed by keepat! in #42351

julia> keepat!([:a, :b, :c], [true, false, true])
2-element Vector{Symbol}:
 :a
 :c

@laborg laborg closed this as completed Feb 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
arrays [a, r, r, a, y, s]
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants