What is the difference between x .= and x[:] =

julia> x = [1,2,3]
3-element Vector{Int64}:
 1
 2
 3

In this case they are the same. Are they always the same? What is the difference?

julia> x .= [10, 20, 30]
3-element Vector{Int64}:
 10
 20
 30

julia> x[:] = [11, 21, 31]
3-element Vector{Int64}:
 11
 21
 31

I am not sure the second form (namely x[:] = ...) works with broadcast fusion.

5 Likes

One difference is that x[:] = ... treats x as a vector, while x .= ... uses the actual shape of x:

julia> x = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> x .= [10, 20, 30, 40]
ERROR: DimensionMismatch("array could not be broadcast to match destination")
[...]

julia> x[:] = [10, 20, 30, 40]
4-element Vector{Int64}:
 10
 20
 30
 40

julia> x
2×2 Matrix{Int64}:
 10  30
 20  40
7 Likes