【问题标题】:defining arrays in fortran after dynamic size declaration在动态大小声明后在 fortran 中定义数组
【发布时间】:2015-03-02 14:14:11
【问题描述】:

我是 Fortran 新手,我想要的是我的矩阵大小取决于 N 是偶数还是奇数, 天真地我会尝试类似下面的东西,但这不会编译,如果我删除 if 语句它可以正常工作,

 subroutine f(fMatrix,oMatrix,N)
      implicit none; 
      integer,intent(in)::N
      integer::d2
      if(mod(N,2)==0) then ! if N is even then 1 type of size
        parameter(d2=1)
      else
        parameter(d2=2)
      endif
      double precision,intent(in),dimension(N, d2):: fMatrix
      double precision,intent(out),dimension(N, d2):: oMatrix
      !do stuff here with fMatrix
      oMatrix = fMatrix
 end subroutine f

对此有什么可能的解决方法?不去分配? 我正在使用 f2py,所以这种方式的任何细节都会很方便。

【问题讨论】:

    标签: python arrays fortran f2py


    【解决方案1】:

    我认为这最接近您想要实现的目标:

    subroutine f(fMatrix,oMatrix,N)
      implicit none
      integer,intent(in)                                    :: N
      double precision,intent(in),dimension(N, mod(N,2)+1)  :: fMatrix
      double precision,intent(out),dimension(N, mod(N,2)+1) :: oMatrix
    
      ! ...
      oMatrix = fMatrix
    end subroutine
    

    我个人更喜欢以下解决方案之一:

    1. 由于fMatrixoMatrix 都是虚拟参数 并传递给子例程,您可以使用assumed shape array specifications
    subroutine f(fMatrix,oMatrix,N)
      implicit none
      integer,intent(in)                           :: N
      double precision,intent(in),dimension(:, :)  :: fMatrix
      double precision,intent(out),dimension(:, :) :: oMatrix
    
      ! ...
    end subroutine
    

    现在调用程序需要指定数组的形状。

    1. 在外部定义d2并将其传递给子程序:
    subroutine f(fMatrix,oMatrix,N, d2)
      implicit none
      integer,intent(in)                            :: N, d2
      double precision,intent(in),dimension(N, d2)  :: fMatrix
      double precision,intent(out),dimension(N, d2) :: oMatrix
    
      ! ...
    end subroutine
    

    并调用子程序:

    call f(fMatrix,oMatrix,N,mod(N,2)+1)
    

    【讨论】:

    • 我明白你在说什么,但有没有办法不必从外部指定?因为对于原始程序,我希望 d2 为 N 表示奇数,N+1 表示偶数。我可以在函数本身中传递参数并声明数组,但我想知道是否可以绕过
    • 这可能遗漏了一个重要的想法:显式形状伪参数数组的行为与假定的形状伪参数数组在几个方面完全不同。
    • 在程序中的某个时刻,您必须决定数组的大小。我的猜测是,您想在 Python 中执行此操作,并将数组传递给 Fortran 代码。如果您想在 Fortran 中执行此操作,您可能需要 allocate 数组或使用自动分配。无论哪种方式,由于您将输入传递给子例程并期望输出,因此这些数组必须在调用子例程之前和之后存在。
    • @francescalus:你可能是对的。我在答案中附加了一个带有显式形状虚拟参数的变体。
    • 是的,或者更好:N+1-mod(N,2) 在第一条评论中得到想要的东西!
    猜你喜欢
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 2012-07-14
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    相关资源
    最近更新 更多