Skip to content

true_pos #568

Closed
Closed
@Beliavsky

Description

@Beliavsky

In a Fortran Discourse thread Indexing arrays by an array of logicals I mentioned a true_pos function I had written to simulate logical indexing, and @ivan-pi suggested that it be considered for stdlib. To deal with the case of a lbound /= 1 mentioned by mecej4, I have added an optional lower_bound argument. If tf(:) has the same size as x(:), one can write x(true_pos(tf)) to refer to elements of x where tf is .true. One can also write pack(x,tf), but that cannot appear on the LHS of an assignment. I have used true_pos hundreds of times in my codes -- maybe it would be generally useful. Since Fortran has minloc, maxloc, and findloc, maybe true_pos should be renamed trueloc.

pure function true_pos(tf, lower_bound) result(ipos)
! return in ipos the positions of the true elements in tf(:)
logical, intent(in)           :: tf(:)
integer, intent(in), optional :: lower_bound 
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
if (present(lower_bound)) ipos = ipos + lower_bound - 1
end function true_pos

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueGood for newcomerstopic: utilitiescontainers, strings, files, OS/environment integration, unit testing, assertions, logging, ...

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions