finding specific indices with pointer array

前端 未结 3 1690
北海茫月
北海茫月 2021-01-25 13:24

I am relatively new to Fortran and break my head about one thing for hours now:

I want to write a subroutine for finding the indexes for specific elements in a real 1D

3条回答
  •  悲哀的现实
    2021-01-25 13:29

    A simple way to get the indices of a rank 1 array arr for elements greater than value min is

    indices = PACK([(i, i=LBOUND(arr,1), UBOUND(arr,1))], arr.gt.min)
    

    where indices is allocatable, dimension(:). If your compiler doesn't support automatic (re-)allocation than an ALLOCATE(indices(COUNT(arr.gt.min)) would be needed before that point (with a DEALLOCATE before that if indices is already allocated).

    As explanation: the [(i, i=...)] creates an array with the numbers of the indices of the other array, and the PACK intrinsic selects those corresponding to the mask condition.

    Note that if you are doing index calculations in a subroutine you have to be careful:

    subroutine COMP(arr, min, indices)
      real, intent(in) :: arr(:)
      real, intent(in) :: min
      integer, allocatable, intent(out) :: indices(:)
    
      !...
    end subroutine
    

    arr in the subroutine will have lower bound 1 regardless of the bounds of the actual argument (the array passed) (which could be, say VALS(10:109). You will also then want to pass the lower bound to the subroutine, or address that later.

    [Automatic allocation is not an F90 feature, but in F90 one also has to think about allocatable subroutine arguments

提交回复
热议问题