# How best to maintain collection of indices into 2-d array

I’d like to maintain a collection of index pairs (i,j) into a 2-dimensional array. The list must not contain any repeated elements, and elements can be added and deleted. Set seems to do the trick:

A = Set([(1,1),(3,3)])
union!(A, [(2,2),(3,3)]) # add only new element (2,2)
setdiff!(A, [(3,3)])     # remove item

B = rand(3,3)
let t = 0
for ind in A
i,j = ind
t += B[i,j]
end
end

Is this the best way to do this sort of thing in Julia?

Probably yes. If you need other features of the collection (eg ordering, fallback defaults), check out

1 Like

Depending on the sparsity and what you’re using the indices for, it may be more efficient to use a SparseMatrix{Bool} than a Set.

using SparseArrays
A = sparse([1, 3], [1, 3], ones(Bool, 2))
A[2,2] |= true # add element
A[3,3] &= false # remove element

B = rand(3,3)
t = sum(B .* A) # will have a better memory access pattern than the above for-loops
2 Likes

Thanks for this suggestion. Your reply also pointed me to |= and &=, which are new to me.