Indexing arrays by an array of logicals

I have written a function that returns a vector index from a logical array

function true_pos(tf) result(ipos)
! return in ipos the positions of the true elements in tf(:)
logical, intent(in) :: tf(:)
integer             :: ipos(count(tf))
integer             :: i,j
j = 0
do i=1,size(tf)
   if (tf(i)) then
      j = j + 1
      ipos(j) = i
   end if
end do
end function true_pos

and would write

A(true_pos(B > 0)) = 0

Logical indexing would be convenient, but given a simple alternative I’m not sure it is worth changing the language. If you are referring to array elements but not setting them you can use the expression

pack(A,B>0)

3 Likes