Hi, I’ve been trying to vectorize the following operation
for i = 1:N
arr[i, :, :] .= arr[a, :, :]
end
over the indices ‘i’ as
@. arr[b:c, :, :] = arr[a, :, :]
(where ‘b’ = 1, ‘c’ = N)
such that all of the elements b:c are copied from index ‘a’. However, this throws an error:
DimensionMismatch(“array could not be broadcast to match destination”)
Makes sense, since I’m trying to assign, e.g. a 5x5 array (RHS) to a 2x5x5 array (LHS). What I want is for all the elements sliced on the LHS array to be the elements copied from arr[a, :, :]. Is there a way to do this?
arr[b:c, :, :] .= arr[a:a,:, :] should work.
Note arr[a:a,:,:] is a 1x5x5 array and not a 5x5 array like arr[a,:,:]. This is important to let broadcasting .= know which dimension to replicate on.
As a side note, in case you’re doing this for performance reasons: Loops and general non-vectorized code in Julia have no inherent penalty to them, and can be as fast as (or faster than) vectorized code. So your for loop can stand as-is unless you have some other reason to change it.