Mask on a 1D array

I’m not aware of any existing type that would do this, but you could create your own subtype of AbstractArray which holds onto the original array and the index you want to mask out:

julia> struct MaskedElementArray{T, N, A <: AbstractArray{T, N}} <: AbstractArray{T, N}
         parent::A
         masked_index::Int
       end

julia> function MaskedElementArray(parent::A, masked_index::Integer) where {T, N, A <: AbstractArray{T, N}}
         MaskedElementArray{T, N, A}(parent, masked_index)
       end
MaskedElementArray

julia> Base.size(a::MaskedElementArray) = size(a.parent)

julia> Base.eltype(a::MaskedElementArray) = eltype(a.parent)

julia> function Base.getindex(a::MaskedElementArray, i::Integer)
         if i == a.masked_index
           zero(eltype(a))
         else
           a.parent[i]
         end
       end

julia> x = [1, 2, 3, 4, 5];

julia> mask = 3
3

julia> M = MaskedElementArray(x, mask)
5-element MaskedElementArray{Int64,1,Array{Int64,1}}:
 1
 2
 0
 4
 5

The MaskedElementArray does not copy the contents of its parent array, so it should be as cheap as creating a view.

5 Likes