fortran - 仅对特定数组索引求和

标签 fortran

我正在尝试使用 SUM 内在函数对数组中的一个索引求和,我不想对所有元素求和。下面我提供了一个运行良好的示例代码。

我想知道是否有更简单的方法来做到这一点。如果是这样,我该如何优化这段代码?谢谢

PROGRAM mysample

INTEGER :: i,j
INTEGER, PARAMETER :: nx = 2, ny = 2
REAL, DIMENSION(nx, ny)  :: f
REAL, DIMENSION(nx)  :: a

DO i = 1,nx
DO j = 1,ny
    f(i,j) = i + 2.*j  
END DO
END DO

DO j = 1,ny 
    a(j) = SUM(f(:,j)) !this line sums over the second array index only
END DO

DO i = 1,nx
    PRINT*, a(i) !the output is correct 
END DO

END PROGRAM

最佳答案

您可以对 Sum 使用可选的 Dim 参数

ijb@ijb-Latitude-5410:~/work/stack$ cat sum.f90 
Program mysample

  Implicit None

  Integer :: i,j
  Integer, Parameter :: nx = 2, ny = 2
  Real, Dimension(nx, ny)  :: f
  Real, Dimension(nx)  :: a, b

  Do i = 1,nx
     Do j = 1,ny
        f(i,j) = i + 2.*j  
     End Do
  End Do

  Do j = 1,ny 
     a(j) = Sum(f(:,j)) 
  End Do

  Do i = 1,nx
     Write( *, * ) 'Reference: ' , a(i) !the output is correct 
  End Do

  b = Sum( f, Dim = 1 )

  Write( *, * ) 'Intrinsic: ', b

End Program mysample
ijb@ijb-Latitude-5410:~/work/stack$ gfortran -std=f2008 -Wall -Wextra -fcheck=all -O -g sum.f90 
ijb@ijb-Latitude-5410:~/work/stack$ ./a.out
 Reference:    7.00000000    
 Reference:    11.0000000    
 Intrinsic:    7.00000000       11.0000000 

关于fortran - 仅对特定数组索引求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68239877/

相关文章:

fortran - Fortran intent(inout) 是否传递值的副本,或指向 RAM 地址的指针/引用?

file-io - 将数据按列写入文件(Fortran)

fortran - 链接 2 个具有相同模块名称和子例程名称的库

thread-safety - 线程安全的统一随机数生成器

fortran - 您可以在 Fortran 中重用函数结果吗?

fortran - 矩阵乘法程序 : Error: Unclassifiable statement at (1)

Fortran 使用 write(6,*) 语句

fortran - Fortran 中结果变量的用途是什么?

fortran - 第一列中的 "d"标签,Fortran 77

Fortran 90 - 尝试读取文件末尾之后的内容