Fortran equivalent of numpy.where() function?

2019-01-28 14:55发布

问题:

I would like to do something like this in Fortran:

program where

real :: a(6) = (/ 4, 5, 6, 7, 8, 9 /)

print *, a(a>7)

end program

In Python I would typically do this with NumPy like this:

import numpy

a = numpy.array([ 4, 5, 6, 7, 8, 9])

print a[numpy.where(a>7)]

#or 

print a[a>7]

I've played around, but nothing has worked thus far, but I'm guessing it is fairly simple.

回答1:

I'll extend slightly the answer by @VladimirF as I suspect you don't want to limit yourself to the exact print example.

a>7 returns a logical array corresponding to a with .true. at index where the condition is met, .false. otherwise. The pack intrinsic takes such a mask and returns an array with those elements with .true. in the mask.

However, you can do other things with the mask which may fit under your numpy.where desire. For example, there is the where construct (and where statement) and the merge intrinsic. Further you can use pack again with the mask to get the indices and do more involved manipulations.



回答2:

program where

real :: a(6) = (/ 4, 5, 6, 7, 8, 9 /)

print *, pack(a,a>7)

end program