Does MINLOC work for arrays beginning at index 0? (Fortran 90/95)

前端 未结 2 1224
轻奢々
轻奢々 2020-12-11 08:48

After using C for a while, I went back to Fortran and allocated the arrays in my code from index 0 to N:

real(kind=dp), dimension(:), allocatable :: a 
alloc         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 09:38

    There are two simple methods to handle complication of adjusting the indices obtained from minloc(): One is simply adding lbound() - 1 for all indices, and the other is using an array pointer with 1-based indices. An example code may look like this:

    program test
    implicit none
    integer, allocatable, target :: a(:,:)
    integer, pointer :: anew(:,:)
    integer :: loc(2)
    
    allocate( a( 0:4, 2:5 ), source= 10 )  !! make an array filled with 10
    
    a( 2, 3 ) = -700                       !! set the minimum value
    
    loc(:) = minloc( a )                   !! minloc() receives "a" with 1-based indices
    print *, loc(:)                        !! so we get [3,2]
    print *, a( loc(1), loc(2) )           !! 10 (wrong result...)
    
    !! Method (1) : adjust indices manually
    
    loc(:) = loc(:) + lbound( a ) - 1
    print *, a( loc(1), loc(2) )           !! -700 (now a correct result)
    
    !! Method (2) : use array pointer with 1-based indices
    
    anew( 1:, 1: ) => a
    
    loc(:) = minloc( anew )
    print *, loc(:)                        !! we get [3,2] again
    print *, anew( loc(1), loc(2) )        !! -700  (this time, no need to adjust indices)
    
    end program
    

提交回复
热议问题