Getting the CartesianIndex of specifi array elements

Dear all,

I’m wondering if there is a simple way to get the CartesianIndex of speciic array elements. I’m not trying to build the whole list of CartesianIndices of an array, only of some of them.
I’m asking because in my code I have to generate a big array of a number of dimensions given by the user, and then I need to randomly pick up a few of them (sort of sampling the array), but need to know the indices of that element in the array, as I have to use their values for computing related quantities. That would be something like

a   = randn(10,20,5)  # though it could be randn(10,3) or rand(1,2,3,4,5,6,7) or...
idx = rand(1:length(a))

iterated many times inside a function etc. The question then is: how do I get the CartesianIndex of a[idx]?

Thanks a lot,

Ferran.

You can do CartesianIndices(a)[idx] or rand(CartesianIndices(a)).

3 Likes