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

巧了我就是萌 提交于 2019-11-28 12:49:13

Your array a indeed starts at index 0, but you did not use that. You searched for a minimum of array abs(a(:)). This anonymous array expression starts at 1 as all arrays do by default.

But even if you used a the result would be the same and is consistent with how array argument passing works in Fortran.

The Fortran standard clearly states:

The i subscript returned lies in the range 1 to ei , where ei is the extent of the idimension of ARRAY. If ARRAY has size zero, all elements of the result are zero.

Lower bounds are not automatically passed with the array if you used assumed shape arguments. For example if you have your own function

  function f(arg)
    real :: arg(:)

arg starts always at 1 no matter where the actual argument started in the calling code.

You can change it to start at some other value

  function f(arg)
    real :: arg(-42:)

and it would be indexed starting from that value.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!