I find it useful to define a function where
which takes an array of logical
s and returns the integer
indices of the .true.
values, so e.g.
x = where([.true., .false., .false., .true.]) ! sets `x` to [1, 4].
This function can be defined as
function where(input) result(output)
logical, intent(in) :: input(:)
integer, allocatable :: output(:)
integer :: i
output = pack([(i, i=1, size(input))], input)
end function
With this where
function, your problem can be solved as
my_array(where(my_array>15.0)) = 0
This is probably not the most performant way of doing this, but I think it is very readable and concise. This where
function can also be more flexible than the where
intrinsic, as it can be used e.g. for specific dimensions of multi-dimensional arrays.
Limitations:
Note however that (as @francescalus points out) this will not work for arrays which are not 1-indexed. This limitation cannot easily be avoided, as performing comparison operations on such arrays drops the indexing information, e.g.
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".
For arrays which are not 1-indexed, in order to use this where
function you would need the rather ugly
my_array(where(my_array>15.0)+lbound(my_array)-1) = 0