Update Vector with dot Operator - Different Behavior when using Vector and Other Types

Here is a piece of code:

v1 = [2, 3, 5, 7, 11, 13, 17]
@show v1
v1[1:3] = [1, 2, 3]
@show v1
v1[1:3] .= 0
@show v1
v1[1:3] .= [4, 5, 6]
@show v1
v1[1:3] .= "1"

Output:

v1 = [2, 3, 5, 7, 11, 13, 17]
v1 = [1, 2, 3, 7, 11, 13, 17]
v1 = [0, 0, 0, 7, 11, 13, 17]
v1 = [4, 5, 6, 7, 11, 13, 17]
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64

Closest candidates are:
  convert(::Type{T}, ::T) where T<:Number
   @ Base number.jl:6
  convert(::Type{T}, ::SentinelArrays.ChainedVectorIndex) where T<:Union{Signed, Unsigned}
   @ SentinelArrays C:\Users\andya\.julia\packages\SentinelArrays\lctlI\src\chainedvector.jl:211
  convert(::Type{T}, ::Number) where T<:Number
   @ Base number.jl:7
  ...

Stacktrace:
 [1] fill!(A::SubArray{Int64, 1, Vector{Int64}, Tuple{UnitRange{Int64}}, true}, x::String)
   @ Base .\multidimensional.jl:1112
 [2] copyto!
   @ .\broadcast.jl:964 [inlined]
 [3] materialize!
   @ .\broadcast.jl:914 [inlined]
 [4] materialize!(dest::SubArray{…}, bc::Base.Broadcast.Broadcasted{…})
   @ Base.Broadcast .\broadcast.jl:911
 [5] top-level scope
   @ d:\Projects\Programming\JuliaTests\test.jl:9
Some type information was truncated. Use `show(err)` to see complete types.

Here is my question. .= 0 assigned 0 to the frist three elements. However, .= [4, 5, 6] does not assign this vector to the first three elements, nor an error thrown like assigning string in the next line, or update v1 to [[4, 5, 6], [4, 5, 6], [4, 5, 6], 7, 11, 13, 17].

Is this designed behavior? Assigning a vector to a vector will update elements respectively, whether use or not use a dot operator. Also, this is different when using Integer and String.

julia> v1 = Any[2, 3, 5, 7, 11, 13, 17]
7-element Vector{Any}:
  2
  3
  5
  7
 11
 13
 17

julia> v1[1:3] .= Ref([4,5,6])
3-element view(::Vector{Any}, 1:3) with eltype Any:
 [4, 5, 6]
 [4, 5, 6]
 [4, 5, 6]

julia> v1
7-element Vector{Any}:
   [4, 5, 6]
   [4, 5, 6]
   [4, 5, 6]
  7
 11
 13
 17
julia> v1[1:3] .= "1"
3-element view(::Vector{Any}, 1:3) with eltype Any:
 "1"
 "1"
 "1"

julia> v1
7-element Vector{Any}:
   "1"
   "1"
   "1"
  7
 11
 13
 17

Taking your questions one at a time:

  1. v[1:3] .= [4,5,6] broadcasts over left and right hand side objects, unless told otherwise.
  2. If you want to not broadcast over the RHS, tell Julia not to do so by enclosing the vector in Ref.
  3. But then you need to set up the vector v1 so it can hold objects other than Int. Hence the Any in v1 = Any[2,3,5,7,11,13,17]. This is also why your string assignment fails (not because of broadcasting.
2 Likes