Hello!
I was experimenting with broadcasting as a way to copy arrays and noticed this:
# First method: Broadcasting after =
a = [1,2,3]
b = @. a
b === a # true
# Second method: Broadcasting at the beginning
a = [1,2,3]
@. b = a
b === a # false
# Third method: Multiplying identity
a = [1,2,3]
b = @. 1*a
b === a # false
Is this desired behaviour? Particularly the first two methods
Thanks!
EDIT: I just saw that the second method errors unless previously initialized. Still, the question holds (more or less )
The rest question should be straightforward.
It can be turned to understanding this.
julia> a=[1,2,3]
3-element Vector{Int64}:
1
2
3
julia> b=a
3-element Vector{Int64}:
1
2
3
julia> c=deepcopy(a)
3-element Vector{Int64}:
1
2
3
julia> b===a
true
julia> c===a
false
julia> c==a
true
1 Like
DNF
3
All of those are expected.
But I’m curious: what were you expecting this
to do? The @.
macro adds dots to all operators and function calls, but here there are none. Clearly, this is identical to
b = a
which is just ordinary assignment.
The second one
is equivalent to
b .= a
which does elementwise copying.
5 Likes
Elrod
4
You can do b = identity.(a)
to copy.
Note that unlike copy
, broadcasting can narrow the container types:
julia> x = Union{Float64,Missing}[1.0, 2.0, 3.0]
3-element Vector{Union{Missing, Float64}}:
1.0
2.0
3.0
julia> copy(x)
3-element Vector{Union{Missing, Float64}}:
1.0
2.0
3.0
julia> identity.(x)
3-element Vector{Float64}:
1.0
2.0
3.0
6 Likes
Thanks!!
This was the kind of alternative that I was seeking after understanding the effect of broadcasting.