How to check for an undef value in a Matrix (in Julia) and assign a new value?

645 Views Asked by At

I want to create a matrix A of undefined values and have the following code that works just fine.

A = Matrix{Tuple{Float64, Array{Int64, 1}}}(undef, 100, 100)

Later, I want to check if a particular cell is undefined and if so, assign a value after computing it. I tried isdefined(A, i, j) but that gave an error for too many arguments. How can I check for #undef and assign only if it is undefined?

The documentation on isdefined provides a method only for a single dimensional array, how do I achieve the same on a matrix?

2

There are 2 best solutions below

1
Przemyslaw Szufel On BEST ANSWER

Use isassigned:

julia> A[2,3]=(3.0, [])
(3.0, Any[])

julia> isassigned(A,2,3)
true

julia> isassigned(A,3,3)
false
1
DNF On

You can use the isassigned function (which is mentioned in the help string of isdefined, btw). Like isdefined it appears to only accept linear indices, but you can get those from LinearIndices.

julia> A = Matrix{Tuple{Float64, Array{Int64, 1}}}(undef, 100, 100);

julia> A[5, 4] = (2.1, [5])
(2.1, [5])

julia> isassigned(A, LinearIndices(A)[1, 1])
false

julia> isassigned(A, LinearIndices(A)[5, 4])
true

Edit: As demonstrated in the answer from @PrzemyslawSzufel, you don't need linear indices. Seems to be be undocumented, though, up to and including v1.5.1