Is it possible in modern Fortran to use a vector to index a multidimensional array? That is, given, say,
integer, dimension(3) :: index = [4,6,9]
double precision, dimension(10,10,10) :: data
is there a better (more general) way to access data(4,6,9) than writing data(index(1), index(2), index(3))? It would be good not to have to hard-code the rank of the data array.
(Naively I would like to write data(index) but of course this actually means something different – subset “gathering” – requiring data to be a rank-one array itself.)
For what it’s worth this is essentially the same question as multidimensional index by array of indices in JavaScript, but in Fortran instead. Unfortunately the clever answers there won’t work with predefined array ranks.
No. And all the workarounds I can think of are ghastly hacks, you’re better off writing a function to take
dataandindexas arguments and spit out the element(s) you want.You might, however, be able to use modern Fortran’s capabilities for array rank remapping to do exactly the opposite, which might satisfy your wish to play fast-and-loose with array ranks.
Given the declaration
you can define a rank-3 pointer
and then set it like this:
and hey presto, you can now use both rank-3 and rank-1 indices into
data, which is close to what you want to do. I’ve not used this in anger yet, but a couple of simple tests haven’t revealed any serious problems.