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 Refs 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 :slight_smile: Same goes for fill([1,2,3], 5) for example.

2 Likes