36

如果我没记错的话,在 C 中,您可以使用花括号语法轻松地初始化数组:

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

当您希望为数学目的初始化具有特定测试值的矩阵时,如何在 Fortran 中对二维数组执行相同的操作?(无需在单独的语句中对每个元素进行双重索引)

该数组由以下定义

real, dimension(3, 3) :: a

或者

real, dimension(:), allocatable :: a
4

3 回答 3

62

您可以使用reshapeshape内在函数来做到这一点。就像是:

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

但请记住列主要顺序。该数组将是

1   4   7
2   5   8
3   6   9

整形后。

所以要得到:

1   2   3
4   5   6
7   8   9

你还需要转置内在:

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

对于更一般的示例(具有不同维度的可分配二维数组),需要size内在:

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
于 2010-09-14T11:23:57.833 回答
23

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. From these two reasons, initialization through array constructor requires the RESHAPE intrisic function.

In addition to what has already been answered, there is a more direct way of entering the value of a matrix by row instead as by column: reshape has an optional argument ORDER which can be used to modify the order of filling the element of the multidimensional array with the entries of the array constructor.

For instance, in the case of the example in the first answer, one could write:

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

obtaining the filling of the matrix array exactly in the order shown by the lines of code.

The array (/2, 1/) forces the column index (2) to have precedence on the row index (1), giving the desired effect.

于 2016-05-01T11:42:20.583 回答
9

数组初始化可以在数组声明语句本身中完成,如下图:

program test
 real:: x(3) = (/1,2,3/)
 real:: y(3,3) = reshape((/1,2,3,4,5,6,7,8,9/), (/3,3/))
 integer:: i(3,2,2) = reshape((/1,2,3,4,5,6,7,8,9,10,11,12/), (/3,2,2/))

end program test

令我惊讶的是

 real:: y(3,3) = (/(/1,2,3/),(/4,5,6/),(/7,8,9/)/)

编译器接受(尝试过 g95、gfortran)。事实证明shapeof (/(/1,2,3/),(/4,5,6/),(/7,8,9/)/)is9和 not 3 3

于 2014-06-23T07:07:49.400 回答