Copying of arrays and array elements

Hey guys!

I discovered this kind of behaviour in Julia. Say that I define a vector as as:

a = [1 2 3]

Then I define:

b = a[2]


c = a

If I now change a by:

a[2] = 4
1×3 Array{Int64,2}:
 1  4  3

Then c becomes:

1×3 Array{Int64,2}:
 1  4  3

But b is still:

b = 2

So my question is, how do I turn of this behaviour / or control it? Could I copy a without later a change in a would become a change in c? And am I able to do it in a way so that b changes corresponding to the element change at index 2 of a, as defined initially (b = a[2])?

I hope my question makes sense. I am using Julia 1.2.0

Kind regards

Yes. As you said yourself, you can copy(a) and then changing a won’t change in the copied a that you assign to c.

You cannot do b = 2 and observe it in a or assign to a[2] = 3 while making b == 2.
You can create a view of the array as b = @view a[2]. Note that b will NOT be a number anymore.

Thanks for clarifying! I have one follow up question. When I use @view you say that it is not a number anymore. Could you elaborate on that a bit? I am still able to say b+b and it will output a number.

Kind regards


julia> a = [1, 2, 3]
3-element Array{Int64,1}:

julia> b = @view a[1]
0-dimensional view(::Array{Int64,1}, 1) with eltype Int64:

julia> b + 1
ERROR: MethodError: no method matching +(::SubArray{Int64,0,Array{Int64,1},Tuple{Int64},true}, ::Int64)
Closest candidates are:
  +(::Any, ::Any, ::Any, ::Any...) at operators.jl:529
  +(::Complex{Bool}, ::Real) at complex.jl:297
  +(::Missing, ::Number) at missing.jl:115
 [1] top-level scope at REPL[3]:1

julia> b + b
0-dimensional Array{Int64,0}:

julia> isa(b, Number)

julia> isa(b, AbstractArray)

It’s not a Number, it’s an (abstract) array.

Behavioral wise, just because you can add it to itself doesn’t means it’s a number and indeed the result of that isn’t a number (this might have produced a number on 1.0/1.1 and was changed/fixed on master) In either case, adding a number to it doesn’t work.

Great, thanks once again.

Kind regards