finding specific indices with pointer array

前端 未结 3 1657
北海茫月
北海茫月 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:34

    I think you're on the right track, but you're ignoring some intrinsic Fortran functions, specifically count, and you aren't returning anything!

    subroutine comp(arr, min)
       real, intent(in) :: arr(:)
       real, intent(in) :: min
    ! local variables
       integer, allocatable :: indices(:)
       integer :: i,j, indx
    
    
    ! count counts the number of TRUE elements in the array 
       indx = count(arr > min)
       allocate(indices(indx))
    
    ! the variable j here is the counter to increment the index of indices
       j=1
       do i=1,size(arr)
          if(arr(i) > min) then
             indices(j) = i
             j = j+1
          endif
       enddo
    end subroutine comp
    

    Then you can use the array indices as

    do i=1,size(indices)
       var = arr(indices(i))
    enddo
    

    Note that since you are not returning indices, you will lose all the information found once you return--unless you plan on using it in the subroutine, then you're okay. If you're not using it there, you could define it as a global variable in a module and the other subroutines should see it.

提交回复
热议问题