SUM(ARRAY, DIM, MASK) or SUM(ARRAY, MASK)

Purpose

Calculates the sum of selected elements in an array.

Class

Transformational function

Argument type and attributes

ARRAY
is an array of numeric type, whose elements you want to sum.
DIM (optional)
is an integer scalar in the range 1 ≤ DIM ≤ rank(ARRAY).
MASK (optional)
is a logical expression. If it is an array, it must conform with ARRAY in shape. If MASK is a scalar, the scalar value applies to all elements in ARRAY.

Result value

If DIM is present, the result is an array of rank rank(ARRAY)-1, with the same data type and kind type parameter as ARRAY. If DIM is missing, or if MASK has a rank of one, the result is a scalar.

The result is calculated by one of the following methods:
Method 1:
If only ARRAY is specified, the result equals the sum of all the array elements of ARRAY. If ARRAY is a zero-sized array, the result equals zero.
Method 2:
If ARRAY and MASK are both specified, the result equals the sum of the array elements of ARRAY that have a corresponding array element in MASK with a value of .TRUE.. If MASK has no elements with a value of .TRUE., the result is equal to zero.
Method 3:
If DIM is also specified, the result value equals the sum of the array elements of ARRAY along dimension DIM that have a corresponding true array element in MASK.
Because both DIM and MASK are optional, various combinations of arguments are possible. When the -qintlog option is specified with two arguments, the second argument refers to one of the following:
  • MASK if it is an array of type integer, logical, byte or typeless
  • DIM if it is a scalar of type integer, byte or typeless
  • MASK if it is a scalar of type logical

Examples

Method 1:
! Sum all the elements in an array.
       RES = SUM( (/2, 3, 4 /) )
! The result is 9 because (2+3+4) = 9
Method 2:
! A is the array (/ -3, -7, -5, 2, 3 /)
! Sum all elements that are greater than -5.
       RES = SUM( A, MASK = A .GT. -5 )
! The result is 2 because (-3 + 2 + 3) = 2
Method 3:
! B is the array | 4 2 3 |
!                | 7 8 5 |

! Sum the elements in each column.
       RES = SUM(B, DIM = 1)
! The result is | 11 10 8 | because (4 + 7) = 11
!                                   (2 + 8) = 10
!                                   (3 + 5) =  8

! Sum the elements in each row.
       RES = SUM(B, DIM = 2)
! The result is | 9 20 | because (4 + 2 + 3) =  9
!                                (7 + 8 + 5) = 20

! Sum the elements in each row, considering only
! those elements greater than two.
       RES = SUM(B, DIM = 2, MASK = B .GT. 2)
! The result is | 7 20 | because (4 + 3) =  7
!                                (7 + 8 + 5) = 20