我发现定义一个函数 where 很有用,它接受 logicals 的数组并返回 .true. 值的 integer 索引,例如
x = where([.true., .false., .false., .true.]) ! sets `x` to [1, 4].
这个函数可以定义为
function where(input) result(output)
logical, intent(in) :: input(:)
integer, allocatable :: output(:)
integer :: i
output = pack([(i, i=1, size(input))], input)
end function
有了这个where函数,你的问题就可以解决了
my_array(where(my_array>15.0)) = 0
这可能不是最高效的方式,但我认为它非常易读和简洁。这个where 函数也可以比where 内在函数更灵活,因为它可以用于例如用于多维数组的特定维度。
限制:
但是请注意(正如@francescalus 指出的那样)这不适用于非 1 索引的数组。这种限制无法轻易避免,因为对此类数组执行比较操作会丢弃索引信息,例如
real :: my_array(-2,2)
integer, allocatable :: indices(:)
my_array(-2:2) = [1,2,3,4,5]
indices = my_array>3
write(*,*) lbound(indices), ubound(indices) ! Prints "1 5".
对于不是 1-indexed 的数组,为了使用这个 where 函数,你需要相当丑陋的
my_array(where(my_array>15.0)+lbound(my_array)-1) = 0