Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize two-dimensional arrays in Fortran

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 
like image 362
Fludlu McBorry Avatar asked Sep 14 '10 11:09

Fludlu McBorry


People also ask

How do I initialize a 2D array in Fortran?

For multidimensional (rank>1) arrays, the Fortran way for initialization differs from the C solution because in C multidimensional arrays are just arrays of arrays of etc. In Fortran, each rank corresponds to a different attribute of the modified data type. But there is only one array constructor, for rank-1 arrays.

How do you create an array in Fortran?

Declaring ArraysArrays are declared with the dimension attribute. The individual elements of arrays are referenced by specifying their subscripts. The first element of an array has a subscript of one. The array numbers contains five real variables –numbers(1), numbers(2), numbers(3), numbers(4), and numbers(5).

How do you declare an array with two dimensions?

We can declare a two-dimensional integer array say 'x' of size 10,20 as: int x[10][20]; Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and 'j' is the column number.


1 Answers

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 

after reshaping.

So to get:

1   2   3 4   5   6 7   8   9 

you also need 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 needs 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 
like image 63
Wildcat Avatar answered Sep 18 '22 12:09

Wildcat