Fortran:选择可分配数组的排名 [英] Fortran: Choosing the rank of an allocatable array

查看:197
本文介绍了Fortran:选择可分配数组的排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,我希望可分配数组 A 具有1,2或3级别,这取决于我在运行时的输入。我希望这样做,因为后续对 A 的操作是相似的,并且我在模块中定义了一个接口 work 模块过程在 A 上执行时会给出所需的结果。

I am trying to write a program where I want the allocatable array A to be of either rank 1, 2, or 3, depending on my input at run-time. I want to do this since the subsequent operations on A are similar, and I have defined in a module an interface work with module procedures that when acted on A, gives the desired result.

目前我所做的是:

What I am doing currently is this:

program main
implicit none
integer :: rank,n=10
real*8, allocatable :: A1(:)
real*8, allocatable :: A2(:,:)
read (*,*) rank

if (rank.eq.1) then
    allocate (A1(n))
else if (rank.eq.2) then
    allocate (A2(n,n))
end if

! operate on the array
if (rank.eq.1) then
    call work(A1)
else if (rank.eq.2) then
    call work(A2)
end if

end program

如果事情会更容易不知何故,我可以选择 A 的等级,因为不需要 if if 语句。也许这是不可能的,但是所有的帮助都会被赞赏。

Things would be much easier if somehow I could choose the rank of A, as then the if statements are not needed. Maybe this is not possible, but all help are appreciated.

推荐答案

声明数组为三。如果需要较低的等级数组,则将相关的尾随维度分配为一个大小。

Declare the array to be rank three. If a lower rank array is required, allocate the relevant trailing dimensions to be of size one.

real, allocatable :: array(:,:,:)
...
select case (desired_rank)
case (1) ; allocate(array(n,1,1))
case (2) ; allocate(array(n,n,1))
case (3) ; allocate(array(n,n,n))
case default ; error stop 'bad desired rank'
end select

然后,您可以使用数组节得到一个与你想要的等级一致的 array 连续片段。或者,编写对数组进行操作的相关过程以获得三级参数,并让他们意识到更高维度的一个范围的含义。

You can then use an array section to get a contiguous slice of array that is consistent with your desired rank. Alternatively, write the relevant procedures that operate on array to take a rank three argument, and make them aware of the meaning of a size one extent for the higher dimensions.

这篇关于Fortran:选择可分配数组的排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆