Suppose I have two arrays A, B
of different sizes. Then A .+ B
broadcasts them to a common size (if possible) and sums them. Suppose A
here is “larger” (in the sense that all(size(B) .== size(A) .|| size(B) .== 1)
is true).
Given an index i
of A
(A[i]
), how can I compute j
such that B[j]
gives the element of B
that would be summed to A[i]
in the broadcasted expression?
My motivation for this question, is that I am trying to code an in-place version of the following function:
function swap(conditions::Union{AbstractArray{Bool}, Bool}, x, y)
x_new = ifelse.(conditions, y, x)
y_new = ifelse.(conditions, x, y)
return x_new, y_new
end
The following:
function swap!(x::AbstractArray, y::AbstractArray, conditions::AbstractArray{Bool})
if size(x) == size(y) == size(conditions)
for i in eachindex(x, y, conditions)
if conditions[i]
x[i], y[i] = y[i], x[i]
else
x[i], y[i] = x[i], y[i]
end
end
return x, y
else
throw(DimensionMismatch("x, y and conditions must have the same size"))
end
end
works if x, y, conditions are of the same size. I would like to relax that, requiring that x,y
be of the same size, but conditions
need only be “broadcastable” to a matching size.