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

**URL:** <https://discourse.julialang.org/t/how-to-insert-a-constant-element-at-a-list-of-indices-of-a-vector-of-vectors-matrices/92503>\
**Category:** General Usage\
**Tags:** broadcasting\
**Created:** [January 4, 2023, 12:28pm UTC](https://discourse.julialang.org/t/how-to-insert-a-constant-element-at-a-list-of-indices-of-a-vector-of-vectors-matrices/92503 "2023-01-04T12:28:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![empet](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/empet/32/221303_2.png) [@empet](https://discourse.julialang.org/u/empet)\
**Post date:** [January 4, 2023, 12:28pm UTC](https://discourse.julialang.org/t/how-to-insert-a-constant-element-at-a-list-of-indices-of-a-vector-of-vectors-matrices/92503/1 "2023-01-04T12:28:40Z")

</div>

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

```julia
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
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.

---

<div class="post-metadata">

**Author:** ![empet](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/empet/32/221303_2.png) [@empet](https://discourse.julialang.org/u/empet)\
**Post date:** [January 4, 2023, 12:43pm UTC](https://discourse.julialang.org/t/how-to-insert-a-constant-element-at-a-list-of-indices-of-a-vector-of-vectors-matrices/92503/2 "2023-01-04T12:43:23Z")

</div>

I found a solution, but I’m waiting for a better one:

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

```

---

<div class="post-metadata">

**Author:** ![skleinbo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/skleinbo/32/36080_2.png) [@skleinbo](https://discourse.julialang.org/u/skleinbo)\
**Post date:** [January 4, 2023, 12:49pm UTC](https://discourse.julialang.org/t/how-to-insert-a-constant-element-at-a-list-of-indices-of-a-vector-of-vectors-matrices/92503/3 "2023-01-04T12:49:52Z")

</div>

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

```julia
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.
