如何在 Fortran 中声明数组变量及其大小中间例程 [英] How to declare an array variable and its size mid-routine in Fortran

查看:52
本文介绍了如何在 Fortran 中声明数组变量及其大小中间例程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个数组,其维度基于另一个数组中满足特定条件的元素数量.这需要我初始化一个数组中间例程,而 Fortran 不允许我这样做.

I would like to create an array with a dimension based on the number of elements meeting a certain condition in another array. This would require that I initialize an array mid-routine, which Fortran won't let me do.

有办法解决吗?

例程示例:

subroutine example(some_array)

real some_array(50) ! passed array of known dimension

element_count = 0
do i=1,50
  if (some_array.gt.0) then
    element_count = element_count+1
  endif
enddo

real new_array(element_count) ! new array with length based on conditional statement

endsubroutine example

推荐答案

您的问题不是关于初始化一个数组,它涉及设置其值.

Your question isn't about initializing an array, which involves setting its values.

但是,有一种方法可以做您想做的事.你甚至可以选择,这取决于它的普遍性.

However, there is a way to do what you want. You even have a choice, depending on how general it's to be.

我假设 element_count 意味着在该循环中有一个 some_array(i).

I'm assuming that the element_count means to have a some_array(i) in that loop.

您可以使 new_array 可分配:

subroutine example(some_array)
  real some_array(50)
  real, allocatable :: new_array(:)

  allocate(new_array(COUNT(some_array.gt.0)))
end subroutine

或者将其作为自动对象:

Or have it as an automatic object:

subroutine example(some_array)
  real some_array(50)
  real new_array(COUNT(some_array.gt.0))
end subroutine

后者仅在您的条件简单"时才有效.此外,不能在模块或主程序范围内使用自动对象.allocable 的情况更为普遍,例如当您想要使用完整循环而不是 count 内在函数时,或者希望变量不作为过程局部变量时.

This latter works only when your condition is "simple". Further, automatic objects cannot be used in the scope of modules or main programs. The allocatable case is much more general, such as when you want to use the full loop rather than the count intrinsic, or want the variable not as a procedure local variable.

在这两种情况下,您都满足在可执行语句之前拥有所有声明的要求.

In both of these cases you meet the requirement of having all the declarations before executable statements.

自 Fortran 2008 以来,block 结构允许自动对象,即使在可执行语句之后和主程序中:

Since Fortran 2008 the block construct allows automatic objects even after executable statements and in the main program:

program example

  implicit none

  real some_array(50)
  some_array = ...

  block
    real new_array(COUNT(some_array.gt.0))
  end block

end program example

这篇关于如何在 Fortran 中声明数组变量及其大小中间例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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