0

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.

Enlico
  • 23,259
  • 6
  • 48
  • 102
  • As part of this question you presumably also care about the function result being an array of some arbitrary (but related) size? – francescalus Feb 05 '16 at 09:56
  • Well, I'd like to know the most general answer, but a first step would be to answer in the case the function gives a scalar as output. – Enlico Feb 05 '16 at 10:24

1 Answers1

2

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.

  • I dont't want to give the size explicitly, so I first and third ways are needed, but I don't know what's the difference; neither I know which way I should use a module.. (I'm new to fortran) – Enlico Feb 05 '16 at 11:10
  • You must read a textbook then. And search stackoverflow. There are good questions and answers about this. For advanced work with arrays you need modules. – Vladimir F Героям слава Feb 05 '16 at 11:13
  • http://stackoverflow.com/questions/8412834/correct-use-of-modules-subroutines-and-functions-in-fortran http://stackoverflow.com/questions/1240510/how-do-you-use-fortran-90-module-data http://stackoverflow.com/questions/11953087/proper-use-of-modules-in-fortran – Vladimir F Героям слава Feb 05 '16 at 11:15