Mask on a 1D array

Hello,

I would like to create a “mask” of a n-dimensional vector x whose i-th entrance is masked by 0, i.e xmask = [x1; x2; ...;xi-1; 0; xi+1; ...; xn]

Is it possible to do this with a “view” and avoid to create a whole new 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

Thank you @rdeits !