如何初始化Fortran的二维数组 [英] How to initialize two-dimensional arrays in Fortran
问题描述
在C,可使用大括号语法容易初始化数组,如果我没有记错:
为int * A = INT新[] {1,2,3,4};
当你想初始化数学目的特定测试值的矩阵二维数组你该怎么办Fortran中一样吗? (而不必加倍指数在单独的语句的每一个元素)
该数组或者通过
定义 真实的,尺寸(3,3)::一
或
真实的,尺寸(:),可分配::一
您可以做到这一点使用重塑和<一个HREF =http://fortranwiki.org/fortran/show/shape>图形内部函数。是这样的:
INTEGER,DIMENSION(3,3)::阵列
阵=重塑((/ 1,2,3,4,5,6,7,8,9 /),形状(阵列))
但要记住列优先的顺序。该阵列将
1 4 7
2 5 8
3 6 9
ARTER整形。
因此,要获得
1 2 3
4 5 6
7 8 9
人们也无需转内在的:
数组=转置(重塑((/ 1,2,3,4,5,6,7,8,9 /),形状(阵列)))
有关更一般的例子(不同尺寸的可分配二维数组)一个需要大小内在的:
程序的主 隐式NONE INTEGER,DIMENSION(:, :),可分配::阵列 ALLOCATE(阵列(2,3)) 阵=转置(重塑((/ 1,2,3,4,5,6 /),放大器;
(/尺寸(阵列,2),尺寸(数组,1)/))) DEALLOCATE(阵列)END程序的主
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
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
这篇关于如何初始化Fortran的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!