12

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.

1 Answer 1

12

No. And all the workarounds I can think of are ghastly hacks, you're better off writing a function to take data and index as 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

double precision, dimension(1000), target :: data

you can define a rank-3 pointer

double precision, pointer :: index_3d(:,:,:)

and then set it like this:

index_3d(1:10,1:10,1:10) => data

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.

2
  • 1
    @VladimirF: well, I can now do data(sum([((index(i)-1)*10**(i-1), i=1, size(index))]) + 1)... if I really want to!
    – Aant
    Aug 18, 2012 at 18:51
  • 1
    @HighPerformanceMark: confirmation that there isn't a nice native way of doing this, and two sensible ways of getting around it... thanks!
    – Aant
    Aug 18, 2012 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.