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

查看:179
本文介绍了如何在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 allocateable :

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

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

或将其作为自动对象:

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

仅当您的情况为简单"时,后者才有效.此外,自动对象不能在模块或主程序的范围内使用. allocatable 的情况更为普遍,例如,当您要使用完整循环而不是内部的 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天全站免登陆