8.261 SUM — Sum of array elements

Description:

Adds the elements of ARRAY along dimension DIM if the corresponding element in MASK is TRUE.

Standard:

Fortran 90 and later

Class:

Transformational function

Syntax:
RESULT = SUM(ARRAY[, MASK])
RESULT = SUM(ARRAY, DIM[, MASK])
Arguments:
ARRAYShall be an array of type INTEGER, REAL or COMPLEX.
DIM(Optional) shall be a scalar of type INTEGER with a value in the range from 1 to n, where n equals the rank of ARRAY.
MASK(Optional) shall be of type LOGICAL and either be a scalar or an array of the same shape as ARRAY.
Return value:

The result is of the same type as ARRAY.

If DIM is absent, a scalar with the sum of all elements in ARRAY is returned. Otherwise, an array of rank n-1, where n equals the rank of ARRAY, and a shape similar to that of ARRAY with dimension DIM dropped is returned.

Example:
PROGRAM test_sum
  INTEGER :: x(5) = (/ 1, 2, 3, 4 ,5 /)
  print *, SUM(x)                        ! all elements, sum = 15
  print *, SUM(x, MASK=MOD(x, 2)==1)     ! odd elements, sum = 9
END PROGRAM
See also:

PRODUCT — Product of array elements