Search code examples
fortran

sum over a specific array index only


I am trying to use the SUM intrinsic to sum over only one index in an array, I do not want to sum over all of the elements. Below I provide a sample code that works fine.

I was wondering if there is an easier way to do this though. If so, how can I optimize this code? Thanks

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

Solution

  • You can use the optional Dim argument to Sum

    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