# Mask on a 1D array

**URL:** <https://discourse.julialang.org/t/mask-on-a-1d-array/42740>\
**Category:** Performance\
**Created:** [July 8, 2020, 3:41pm UTC](https://discourse.julialang.org/t/mask-on-a-1d-array/42740 "2020-07-08T15:41:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mleprovost](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mleprovost/32/7166_2.png) [@mleprovost](https://discourse.julialang.org/u/mleprovost)\
**Post date:** [July 8, 2020, 3:41pm UTC](https://discourse.julialang.org/t/mask-on-a-1d-array/42740/1 "2020-07-08T15:41:16Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [July 8, 2020, 3:55pm UTC](https://discourse.julialang.org/t/mask-on-a-1d-array/42740/2 "2020-07-08T15:55:23Z")

</div>

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
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`.

---

<div class="post-metadata">

**Author:** ![mleprovost](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mleprovost/32/7166_2.png) [@mleprovost](https://discourse.julialang.org/u/mleprovost)\
**Post date:** [July 8, 2020, 3:59pm UTC](https://discourse.julialang.org/t/mask-on-a-1d-array/42740/3 "2020-07-08T15:59:05Z")

</div>

Thank you @rdeits !
