从其他数组继承大小的简洁表示法? [英] Concise notation for inheriting size from other array?
问题描述
在我的代码中,我有一个子例程,它接受一个 5 阶数组作为参数并使用一个局部变量,这是一个共享前 4 个索引的 4 阶数组.
In my code, I have a subroutine that takes a 5th-rank array as argument and uses a local variable, which is a 4-th rank array sharing the first 4 indices.
我正在尝试找到一种更简洁的方式来表达尺寸声明
I'm trying to find a more concise way to express the size declaration in
subroutine mysub(momentum)
complex, intent(in) :: momentum(:,:,:,:,:)
complex :: prefactor( &
& size(momentum,1), size(momentum,2), size(momentum,4) &
& size(momentum,5) )
...
end subroutine mysub
冗长的大小声明会损害可读性,尤其是当变量名比这里更长的时候.
The verbosity of the size declaration harms readability, especially when variable names are even longer than here.
如果这是 octave/matlab 我会预先分配 prefactor
通过编写
If this was octave/matlab I'd pre-allocate prefactor
by writing
prefactor = zeros(size(momentum)([1 2 4 5]))
Fortran 90 是否支持类似简洁的东西?我知道可以使用预处理器宏来解决它,例如
Does Fortran 90 support something similarly concise? I know that it could be solved using preprocessor macros, such as
#define XSIZE2(array,a,b) SIZE(array,a), SIZE(array,b)
#define XSIZE3(array,a,b,c) SIZE(array,a), SIZE(array,b), SIZE(array,c)
#define XSIZE4(array,a,b,c,d) SIZE(array,a), SIZE(array,b), SIZE(array,c), SIZE(array,d)
但是引入这样的定义可能会损害可读性而不是帮助.
but introducing such definitions would probably harm the readability more than it helps.
推荐答案
Fortran 2008 在 allocate
语句中添加了 mold
说明符.如果您可以访问支持此功能的编译器,您可以尝试
Fortran 2008 added the mold
specifier to the allocate
statement. If you have access to a compiler that supports this feature, you can try
program main
implicit none
integer :: a(2,3,4,5,6)
integer, allocatable :: b(:,:,:,:)
print *, shape(a)
allocate(b, mold=a(:,:,:,:,1))
print *, shape(b)
end program main
此代码段适用于 Intel Fortran 2016,更新 1.
This snippet worked with Intel Fortran 2016, Update 1.
这篇关于从其他数组继承大小的简洁表示法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!