# Assigning array to a slice of another array

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.

1 Like

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.

1 Like

Another thing is that Julia `Array`s are column major, unlike in numpy/C++/etc. So it would be (possibly much) faster to arrange your data so you can do

``````arr[:, :, i] .= arr[:, :, a]
``````

In general, it’s a good idea to take this into account when designing your data layout.

1 Like

For better performance, you may consider using views:

``````arr[i, :, :] .=  view(arr, a, :, :)
``````

Thanks for the tip, I’ll see if I can do so!

Thanks, I’ve added the @views macro to the relevant lines.