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
572 views
in Technique[技术] by (71.8m points)

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

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 
allocate(a(0:50))

I needed to find the index of the minimum absolute value of the array, so I used MINLOC, and to check this I compared it to MINVAL:

minloc(abs(a(:)))
minval(abs(a))

The result of MINLOC was index 42 but the result of MINVAL corresponded to 41. Here is the relevant section from the output:

Index i    a(i) 

39         0.04667    
40         0.02222    
41         0.00222           !This was clearly the minimum value
42         0.02667

MINLOC = 42
MINVAL = 0.00222

I assume this is something to do with the Fortran intrinsic not handling arrays with index 0 correctly, since it is not standard Fortran style to declare arrays in this way (but it is still permitted!).

Can anyone confirm this or offer a workaround?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


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

...