【问题标题】:Defining an Array with Non-Consecutive Indices in Fortran在 Fortran 中定义具有非连续索引的数组
【发布时间】:2018-11-05 08:09:42
【问题描述】:

是否可以在 Fortran 90 中定义具有非连续索引的数组?


以下代码返回错误(Error: The module or main program array 'test' at (1) must have constant shape):

program example
  implicit none
  integer, dimension((/1,3/)) :: test
end

是否有另一种方法来定义这样的数组,或者这根本不允许?

【问题讨论】:

  • 为什么你认为你需要这个?
  • 它将帮助我解决this question中的问题。
  • @mzp 您的问题的答案是“否”和“是”。数组维度的下限和上限是规范表达式。规范表达式是一个标量整数表达式。
  • 好的,谢谢你的帮助!
  • 而不是像那样尝试疯狂,你有没有想过如何将你的问题向量化,这样你就不需要不连续的索引?

标签: arrays fortran fortran90


【解决方案1】:

您可以自己实现该类型。这是一种混乱且低效的方法。

module WeirdArray
  implicit none
  private

  type, public :: Warray
    private
    integer, dimension(:), allocatable :: indeces
    real, dimension(:), allocatable :: vals
  contains
    procedure, pass :: init
    procedure, pass :: get
    procedure, pass :: set
  end type

contains
  subroutine init(this, i, v)
    class(warray), intent(out) :: this
    integer, dimension(:) :: i
    real, dimension(size(i)) :: v
    this%indeces = i
    this%vals = v
  end subroutine init

  function get(this, indx) result(x)
    class(warray), intent(in) :: this
    integer, intent(in) :: indx
    real :: x
    integer, dimension(:), allocatable :: p
    integer :: i
    p = pack([(i,i=1,size(this%indeces))],this%indeces==indx)
    x = this%vals( p(1) )
  end function get

  subroutine set(this, indx, x)
    class(warray), intent(inout) :: this
    integer, intent(in) :: indx
    real, intent(in) :: x
    integer, dimension(:), allocatable :: p
    integer :: i
    p = pack([(i,i=1,size(this%indeces))],this%indeces==indx)
    this%vals( p(1) ) = x
  end subroutine set  

end module WeirdArray

你可以这样使用它:

program main
  use weirdArray
  implicit none

  type(Warray) :: wa

  call wa%init([5,12], [10.0, 24.0])

  write(*,*) wa%get(5)
  call wa%set(5, 3.14)
  write(*,*) wa%get(5)
  write(*,*) wa%get(12)

end program main

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-27
    • 2011-01-18
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多