# How to insert a constant element at a list of indices of a Vector of Vectors/Matrices

I have a vector of `QuatRotation{Float64}`, defined initially as:

``````Q = Vector{QuatRotation{Float64}}(undef, 10)
``````

and a vector of indices ids= [1, 4, 7]. I want to insert at each index β ids, the rotation `Rotations.UnitQuaternion(0,0,1,0)`. I expected to be allowed to assign this QuatRotation, as follows:

``````julia> Q[ids] .= UnitQuaternion(0, 0, 1, 0)
ERROR: DimensionMismatch: cannot broadcast array to have fewer non-singleton dimensions
``````

but it throws this error.
Obviously I can assign it with a for loop, but Iβd like a more concise way.

I found a solution, but Iβm waiting for a better one:

``````Q = Vector{QuatRotation{Float64}}(undef, 10)
ids= [1,3, 7]
Q[ids]= repeat([UnitQuaternion(0, 0, 1, 0)], 3)
``````

`QuatRotation` is not a scalar with respect to broadcasting. Using

``````Q[ids] .= Ref(UnitQuaternion(0, 0, 1, 0))
``````

works, because `Ref`s are treated as scalars.

Note however that this is dangerous when the right hand side is mutable / has mutable fields, i.e. a `Vector{...}`, because that will assign the same object to every index on the left. Not a problem here, but itβs a trap Iβve fallen in more times than I like to admit Same goes for `fill([1,2,3], 5)` for example.

2 Likes