How to convert multi-dimensional indices into one-dimensional indices

A = rand(3,3)
b = findall(A .> .5)

For instance:

3-element Vector{CartesianIndex{2}}:
CartesianIndex(1,1)
CartesianIndex(3,1)
CartesianIndex(2,2)

How to do if I want b to contain the corresponding Int to access the array ? (and not CartesianIndex) Is there a way to transform b in Int such that the values still correspond to the location in the array A ?

For instance, if the CartesianIndex is (1,1) then the corresponding Int is 1 and A[1] gives access to the first element of the array whatever its dimensions.

Here is a simple way of doing that:

A = rand(3, 3)
I = CartesianIndex(1, 2)
LinearIndices(A)[I]  # returns 4
2 Likes

It works !

When writing A in LinearIndices, does it load the full array ? If yes, is there a way to only give the dimensions of A (as we do not need the values in A). If it does not load A, then it is fine.

LinearIndices(A) is lazy, but LinearIndices(A)[b] is not. You can also write findall(vec(A) .> .5), perhaps.

3 Likes