Using MINLOC with Fortran: Incompatible ranks 0 an

2020-02-13 01:49发布

问题:

Version that gives an error message

program hello
   integer a(9)
   integer index; ! note no dimension here
   a=(/1, 3, 4, 5, 6, 7, 8, 9, 10/)
   index = MINLOC(a, MASK=(a > 5))
   Print *, index
end program Hello

Error message

main.f95:5.3:

index = MINLOC(a, MASK=(a > 5)) 1 Error: Incompatible ranks 0 and 1 in assignment at (1)

Working version

program hello
   integer a(9)
   integer index(1) ! note dimension 1 here which looks redundant at first
   a=(/1, 3, 4, 5, 6, 7, 8, 9, 10/)
   index = MINLOC(a, MASK=(a > 5))
   Print *, index
end program Hello

Search

Here I could find related discussion but I don't find it sufficiently verbose for me to understand the difference.

回答1:

You can fix the first version, obtaining a scalar return from minloc, by using the DIM argument:

index = MINLOC(a, DIM=1, MASK=(a > 5))

P.S. No need for semicolons to end statements unless you place multiple statements per line. Fortran isn't C.



回答2:

This discussion brings up an important point: MINLOC returns an array, even if it's only one number, it's still an array.

It may be possible to declare index as an array, like mentioned above, or to use a temporary array.

integer :: temp(1)
...
temp=minloc(dist)
index=temp(1)

It is also possible to use DIM argument to avoid manual fiddling with data types, like mentioned in M.S.B's answer.