Search code examples
matlabfortranfortran90indices

Fortran function that accepts arbitrary sized rank-1 arrays


How can I write a function that accepts arrays of arbitrary size, provided they are of rank 1? This is exactly what the intrinsic function shape can do, so I don't think my request is too demanding. Actually, the function shape does more. It can (obviously) accept array of any shape, that is arbitrary rank and arbitrary length along each dimension.

This question is aimed to write a function sub2ind which corresponds to the MATLAB function of the same name.


Solution

  • I am not sure if I understand your question correctly, but functions accepting any array size were possible in Fortran since Fortran functions were invented. (Although some tricks were sometimes involved before FORTRAN 77). Any textbook or tutorial will treat this problem.

    Modern style assumed shape:

      function f(a)
        real :: a(:)
        do i = 1, size(a)
        ...
      end functions
    

    explicit size:

      function f(n, a)
        real :: a(n)
        do i = 1, n
        ...
      end functions
    

    assumed size:

      function f(n, a)
        real :: a(*)
        do i = 1, n
        ...
      end functions
    

    For assumed shape, explicit interface (best using modules) is necessary.