views:

178

answers:

1

In C you can easily initialize an array using the curly braces syntax, if I remember correctly:

int* a = new int[] { 1, 2, 3, 4 };

How can you do the same in Fortran for two-dimensional arrays when you wish to initialize a matrix with specific test values for mathematical purposes? (Without having to doubly index every element on separate statements)

The array is either defined by

real, dimension(3, 3) :: a

or

real, dimension(:), allocatable :: a
+1  A: 

You can do that using reshape and shape intrinsics. Something like:

INTEGER, DIMENSION(3, 3) :: array
array = reshape((/ 1, 2, 3, 4, 5, 6, 7, 8, 9 /), shape(array))

But remember the column-major order. The array will be

1   4   7
2   5   8
3   6   9

arter reshaping.

So to get

1   2   3
4   5   6
7   8   9

one need also transpose intrinsic:

array = transpose(reshape((/ 1, 2, 3, 4, 5, 6, 7, 8, 9 /), shape(array)))

For more general example (allocatable 2D array with different dimensions) one need size intrinsic:

PROGRAM main

  IMPLICIT NONE

  INTEGER, DIMENSION(:, :), ALLOCATABLE :: array

  ALLOCATE (array(2, 3))

  array = transpose(reshape((/ 1, 2, 3, 4, 5, 6 /),                            &
    (/ size(array, 2), size(array, 1) /)))

  DEALLOCATE (array)

END PROGRAM main
kemiisto
1) Most compilers now accept the Fortran 2003 notation [] to initialize arrays, instead of the somewhat awkward (/ /). 2) For simple cases you can omit transpose by providing the values in the column-major order: array = reshape ( [1, 4, 7, 2, 5, 8, 3, 6, 9 ], shape (array) )
M. S. B.
I forgot to mention that we're required to work in Fortran 90.
Fludlu McBorry