Search code examples
fortranrank

Type conflict of maxloc in Fortran


I have the following Fortran program

PROGRAM main

  IMPLICIT NONE

  INTEGER                          :: i
  INTEGER,dimension(:),allocatable :: x0

  allocate(x0(1:25))
  DO i=1,25
     x0(i)=i
  END DO

  print*,"maxloc de x0 est 25, en effet",maxloc(x0)

  print*,"Cinq fois maxloc(x0)",INT(maxloc(x0))

  print*,"f applique a la fonction",f(maxloc(x0))

  print*,"f1 applique a la fonction",f1(INT(maxloc(x0)))

  CONTAINS

  FUNCTION f(maxlocec)
    IMPLICIT NONE
    !Entrées
    INTEGER,dimension(1) :: maxlocec
    !Sorties
    INTEGER,dimension(1) :: f

    f=maxlocec**2

  END FUNCTION f

  FUNCTION f1(maxlocec)
    IMPLICIT NONE
    !Entrées
    INTEGER :: maxlocec
    !Sorties
    INTEGER :: f1

    f1=maxlocec**2

  END FUNCTION f1

END PROGRAM

when I execute it i get the following error message:

print*,"f1 applique a la fonction",f1(INT(maxloc(x0)))
                                        1
Error: Rank mismatch in argument 'maxlocec' at (1) (0 and 1)

I have tried f1(maxloc(x0)) and it was not working, so I thought f1(INT(maxloc(x0))) would work and it is not.

The output of maxloc seems to be an integer but is not. What it is the way to solve it?


Solution

  • The maxloc routine does not return a scalar integer but, in this case, a 1-dimensional integer array of size 1. From the standard:

    MAXLOC (ARRAY, DIM [, MASK, KIND, BACK]) or MAXLOC (ARRAY [, MASK, KIND, BACK])

    ...

    Result Characteristics. Integer. If KIND is present, the kind type parameter is that specified by the value of KIND; otherwise the kind type parameter is that of default integer type. If DIM does not appear, the result is an array of rank one and of size equal to the rank of ARRAY; otherwise, the result is of rank n − 1 and shape [d1, d2, . . . , dDIM−1, dDIM+1, . . . , dn], where [d1, d2, . . . , dn] is the shape of ARRAY.

    So in your case yo will probably need:

    print*,"f1 applique a la fonction",f1(maxloc(x0,1))