我正在尝试使用 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/