Search code examples
arraysfortrantranslation

Initilalising an array with a sequence in Fortran


I am currently working on translating some legacy fortran code and I am having a hard time understanding a particular line in the code. The compiler also seems to find this line weird and throws out an error. From what I understand it is trying to initialize an array by sequencing 1 to 9 by increments of 1 and filling up the array matrix with this sequence in column major form.

program arrayProg

  integer :: matrix(3,3), i , j !two dimensional real array

  matrix = reshape((/1:9:1/), (/3,3/))

end program arrayProg

Is this syntax acceptable in fortran? (It has to be because it comes from the legacy code) Am I misunderstanding what the line does?


Solution

  • The syntax is incorrect and such code cannot be compiled by a Fortran compiler, unless it implements some non-standard extension.

    Intel Fortran accepts this:

     A colon-separated triplet (instead of an implied-DO loop) to specify a range of values and a stride; for example, the following two array constructors are equivalent:
    1       INTEGER D(3)
    2       D = (/1:5:2/)              ! Triplet form - also [1:5:2]
    3       D = (/(I, I=1, 5, 2)/)     ! implied-DO loop form
    

    from Development Reference Guides:Array Constructors

    (note: The links to Intel Documentation change frequently, if the link is dead, please notify me in the comment and try searching for "triplet form" and "array constructors")

    To generate a sequence in a standard way one uses an implied do loop like

     (/ (i, i=1,9) /)
    

    the reshape then just changes the 1D array into a 2D one in column major order as you guessed.