Problems with FINDLOC command

Dear friends,

Please, I would like to request your help with this problem: given a one dimensional array I have to find the first value that is larger than 0. I know that the way to go is to use FINDLOC but I don’t know how to implement it since, as far as I know, its syntax is FINDLOC( array, scalar), so I cannot figure it out how to include the condition > 0.

Is it possible to obtain a result as an integer or it will always be an integer array?

Many thanks for your help.

Hello @CConde,

to obtain a scalar integer as return value, you need to supply the dim argument of findloc:

If DIM is present and ARRAY has a rank of one, the result is a scalar.

As the array argument you supply an array of logical values obtained from testing your condition. Here is a minimal working example.

implicit none
integer :: a(5), pos
a = [-2, -1, 0, 1, 2]
pos = findloc(a > 0, .true., dim = 1)
print *, pos    ! 4
end
3 Likes

This task occurs often enough that I have defined a function first_true

pure function first_true(tf) result(i1)
! return the location of the first true element in tf(:), 0 if none true
logical, intent(in) :: tf(:)
integer             :: i1
integer             :: i
i1 = 0
do i=1,size(tf)
   if (tf(i)) then
      i1 = i
      return
   end if
end do
end function first_true

and can write

pos = first_true(a>0)

Maybe this utility function is suitable for stdlib.

5 Likes

Now that you mention it, I see some clash with the chosen name for the trueloc function that was added already (true_pos · Issue #568 · fortran-lang/stdlib · GitHub). (If I’m not mistaken, the function in stdlib returns all index positions belonging to true elements.)

1 Like

Maybe it can be called firstloc to be consistent with trueloc and falseloc.

@ivanpribec, @Beliavsky, many thanks for your help.