Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access and change an element in an array with the help of a pointer in Julia?

I have a nested Array and want to repeatedly get the value at a specific location in the array and change it. Is there a way to do this with a pointer to be more compact? I use Julia 1.6.0.

My array looks like this:

Q = Array{Array}(undef, 10,10)
for row in 1:10
    for col in 1:10
        Q[row,col] = Array{Array}(undef, 5,5)
        for i in 1:5
            for j in 1:5
                Q[row,col][i,j] = zeros(9)
            end
        end
    end
end

My current solution is to set a variable to the array one level above the element and to then change it:

tmp = Q[3,3][2,4]
tmp[5] = 1

What I would like to have is some way to directly address the element:

tmp = Q[3,3][2,4][5]
tmp = 1

This doesn't change the array though. I read something auf the Ref() function but didn't quite manage to use it for getting/changing the element.

Thank you in advance!

like image 980
Babypopo Avatar asked Dec 19 '25 10:12

Babypopo


1 Answers

You can make an array of pointers:

julia> a = [Ref(0) for i in 1:2, j in 1:2]
2×2 Matrix{Base.RefValue{Int64}}:
 RefValue{Int64}(0)  RefValue{Int64}(0)
 RefValue{Int64}(0)  RefValue{Int64}(0)

Now you can get one element

b = a[1,2];

You can mutate it:

b[] = 600;

Now we get back to the array to see the result

julia> a
2×2 Matrix{Base.RefValue{Int64}}:
 RefValue{Int64}(0)  RefValue{Int64}(600)
 RefValue{Int64}(0)  RefValue{Int64}(0)

You might also wonder how to get the data:

julia> getindex.(a)
2×2 Matrix{Int64}:
 0  600
 0    0

For most scenarios this is not a recommended approach to work with data though. Have a look at @views instead. Here is an equivalent example:

julia> c=zeros(Int,2,2)
2×2 Matrix{Int64}:
 0  0
 0  0

julia> elem = @view c[1,1]
0-dimensional view(::Matrix{Int64}, 1, 1) with eltype Int64:
0

julia> elem .= 999;


julia> c
2×2 Matrix{Int64}:
 999  0
   0  0
like image 176
Przemyslaw Szufel Avatar answered Dec 21 '25 02:12

Przemyslaw Szufel