Masked array assignment

Viewed 59

I have a NxN array A, a NxN array B and a NxN mask (BitMatrix) M. Now I want to copy / assign the values of B to A only for the indices for which M is true. What is the best way to do that?

1 Answers

You can use logical indexing

julia> A = zeros(5,5); B = ones(5,5); M = rand(Bool, 5, 5)
5×5 Matrix{Bool}:
 1  0  1  1  0
 1  0  1  1  0
 1  0  1  1  1
 0  0  0  1  0
 0  0  0  0  1

julia> A[M] = B[M]; A
5×5 Matrix{Float64}:
 1.0  0.0  1.0  1.0  0.0
 1.0  0.0  1.0  1.0  0.0
 1.0  0.0  1.0  1.0  1.0
 0.0  0.0  0.0  1.0  0.0
 0.0  0.0  0.0  0.0  1.0

or simply write a loop:

julia> for i in eachindex(A, B, M)
           if M[i]
               A[i] = B[i]
           end
       end
Related