Bind variable to element of an array

question

#1

I’m sure it is possible to bind a variable to an element of an array, but wasn’t able to figure out how, does anyone know?


#2

Check out the documentation for the @view macro.

Here’s an example (not sure if this is what you’re looking for or not):

julia> x = rand(2)
2-element Array{Float64,1}:
0.592149
0.600268

julia> x1 = @view x[1]
0-dimensional SubArray{Float64,0,Array{Float64,1},Tuple{Int64},false}:
0.592149

julia> map!(x->x+1,x1)
0-dimensional SubArray{Float64,0,Array{Float64,1},Tuple{Int64},false}:
1.59215

julia> x1
0-dimensional SubArray{Float64,0,Array{Float64,1},Tuple{Int64},false}:
1.59215

julia> x
2-element Array{Float64,1}:
1.59215
0.600268


#3

That’s pretty close. Is there a way to do this without having the number wrapped in a 0-dim array?


#4

I suppose you could define your own Number type that is a view. But otherwise, no: you need a mutable object here, and the built-in number types are immutable.


#5

You don’t really need a mutable type but you do need a reference to the memory. A variable is not allowed to do that but it can be (efficiently) emulated. The closest to what you describe is Ref. You can get a reference to an array slot with Ref(array, index) which is also how you pass such a reference to C.


#6

Could you comment on best practices of mutating this reference? Here’s the best I could come up with:

julia> x = rand(2)
2-element Array{Float64,1}:
0.364822
0.334024

julia> x1 = Ref(x,1)
Base.RefArray{Float64,Array{Float64,1},Void}([0.364822,0.334024],1,nothing)

julia> x1.x[x1.i] += 1
1.3648224629409698

julia> x
2-element Array{Float64,1}:
1.36482
0.334024

I could be misunderstanding the desired use case though, @jebej could you talk more to exactly what you want?


#7

x1[]