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

查看:37
本文介绍了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.

我目前正在做的是:

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 语句了.也许这是不可能的,但感谢所有帮助.

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.

推荐答案

声明数组为第三级.如果需要较低等级的数组,请将相关的尾随维度分配为大小为 1.

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天全站免登陆