Problem placing views into an array

When I add a view into an array, it creates a copy of it instead of creating a reference to the original view. Modifying the view does not modify the array it was added to. This is not the case when the array is not a view. It also seems to depend on the type of the array, Any seems to work.

a=[[1,2,3]]
b=[3,4,5,6]
c=view(b, 2:4)
push!(a,c)
c[3]=1000
@show a
@show c
@show a[2] == c

#result
a = [[1, 2, 3], [4, 5, 6]]
c = [4, 5, 1000]
a[2] == c = false

#desired result
a = [[1, 2, 3], [4, 5, 1000]]
c = [4, 5, 1000]
a[2] == c = true

Is there any way to make this work? I would like to have views so I don’t have to assign new memory or copy arrays around all the time.

The problem is that a is a Vector{Vector{Float64}} so it can’t store views. This would work if you defined a=AbstractVector{Float64}[[1,2,3]], but this will likely cause performance issues since it will introduce type instability.

2 Likes

Thank you. I didn’t even think to try typeof(c) which is SubArray{Int64, 1, Vector{Int64}, Tuple{UnitRange{Int64}}, true}, and creating an array for this type seems to work fine.

I had in my head that views were just like pointers to the middle of another array like in C, which is all I am using them for. Is there any way to achieve that behavior?

Short answer is no. Julia arrays store their size, so a pointer to a location in an array is not an Array.

2 Likes