Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

finding specific indices with pointer array

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 array (given to the routine as input).

I have generated an array with 100 random reals, called arr, and now want to determine the indexes of those elements which are greater than a real value min, which is also passed to subroutine.

Plus, in the end I would like to have a pointer I'd allocate in the end, which I was said would be better than using an array indices containing the indexes once found.

I just didn't find how to solve that, I had following approach:

SUBROUTINE COMP(arr, min)
   real, intent(in)                 :: arr(:)
   real, intent(in)                 :: min
   integer, pointer, dimension(:)   :: Indices
   integer                          :: i, j

   ! now here I need a loop which assigns to each element of the pointer 
   ! array the Indices one after another, i don't know how many indices there
   ! are to be pointed at 
   ! And I dont know how to manage that the Indices are pointed at one after another,
   ! like Indices(1) => 4
   !      Indices(2) => 7
   !      Indices(3) => 32
   !      Indices(4) => 69
   !      ...
   ! instead of
   !      Indices(4) => 4
   !      Indices(7) => 7
   !      Indices(32) => 32
   !      Indices(69) => 69
   !      ...


   DO i = 1, size(arr)
      IF (arr(i) > min) THEN
         ???
      ENDIF
   ENDDO
allocate(Indices)
END SUBROUTINE COMP
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If succinctness (rather than performance) floats your boat... consider:

FUNCTION find_indexes_for_specific_elements_in_a_real_1D_array(array, min)  &
    RESULT(indices)
  REAL, INTENT(IN) :: array(:)
  REAL, INTENT(IN) :: min
  INTEGER, ALLOCATABLE :: indices(:)
  INTEGER :: i
  indices = PACK([(i,i=1,SIZE(array))], array >= min)
END FUNCTION find_indexes_for_specific_elements_in_a_real_1D_array

[Requires F2003. Procedures that have assumed shape arguments and functions with allocatable results need to have an explicit interface accessible where they are referenced, so all well behaved Fortran programmers put them in a module.]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...