如何在 Fortran 中初始化二维数组 [英] How to initialize two-dimensional arrays in Fortran
问题描述
在 C 中,如果我没记错的话,您可以使用花括号语法轻松地初始化数组:
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 };
当您希望使用特定的测试值初始化矩阵以用于数学目的时,如何在 Fortran 中为二维数组执行相同的操作?(不必在单独的语句中对每个元素进行双重索引)
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)
数组由
real, dimension(3, 3) :: a
或
real, dimension(:), allocatable :: a
推荐答案
你可以使用 reshape 和 shape 内在函数.类似的东西:
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
整形后.
所以得到:
1 2 3
4 5 6
7 8 9
您还需要转置内在:
array = transpose(reshape((/ 1, 2, 3, 4, 5, 6, 7, 8, 9 /), shape(array)))
对于更一般的示例(具有不同维度的可分配二维数组),需要 size 内在:
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
这篇关于如何在 Fortran 中初始化二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!