Whole-array operations

This is the part of Fortran that the rest of the language exists for: an operation on an array is written as an operation on a value, and the loop disappears into the compiler. The same syntax compares arrays to make a mask, and the reductions take that mask as an argument. This lesson writes the arithmetic without a loop and then selects part of the data with a mask.

Elementwise arithmetic

An arithmetic operator between two arrays of the same shape applies to every pair of elements. The result has the same shape, and the compiler checks it: integer :: a(3), b(2); b = a is the shape error of the diagnostics lesson.

The file whole.f90:

program whole implicit none integer, parameter :: n = 4 real :: x(n), y(n), z(n) x = [1.0, 2.0, 3.0, 4.0] y = 2.0 * x + 1.0 z = sqrt(x) print *, "x:", x print *, "y:", y print *, "z:", z print *, "sum(x) :", sum(x) print *, "sum(x*y) :", sum(x * y) print *, "maxval(y) :", maxval(y) print *, "minloc(x) :", minloc(x) end program whole

gfortran -Wall -Wextra -std=f2018 whole.f90 -o whole
./whole

x: 1.00000000 2.00000000 3.00000000 4.00000000
y: 3.00000000 5.00000000 7.00000000 9.00000000
z: 1.00000000 1.41421354 1.73205078 2.00000000
sum(x) : 10.0000000
sum(x*y) : 70.0000000
maxval(y) : 9.00000000
minloc(x) : 1

Scalars and whole arrays

A scalar combined with an array is applied to every element, which is why y = 2.0 * x + 1.0 needs no loop and no temporary. The rule is called broadcasting in other languages; in Fortran it is simply what the operator means when one side is a scalar.

An assignment from a scalar fills every element, as zeros = 0 did in the previous lesson. An assignment from a constructor with the wrong number of values is a shape error, and the compiler reports both lengths.

Elemental intrinsics

Most mathematical intrinsics are elemental: given an array they return an array of the same shape. sqrt(x), exp(x), abs(x) and nint(x) all work this way, which is why a formula that reads like the mathematics is also the code. An elemental function a program writes itself, with the elemental prefix, has the same property.

The reduction intrinsics are the other half of the pair: sum, product, maxval, minval, count, any and all take an array and give a scalar, and each of them accepts a dim argument to reduce one dimension of a rank-2 array instead of all of them.

Masks

A comparison between an array and a scalar is an array of logicals, one per element. That value is a mask, and it is the array equivalent of an if: a > 4 says which elements pass. The second program uses it three ways.

The file mask.f90:

program mask implicit none integer, parameter :: n = 6 integer :: a(n) logical :: big(n) a = [3, 8, 1, 9, 2, 7] big = a > 4 print *, "a :", a print *, "a > 4 :", big print *, "any :", any(big) print *, "all :", all(big) print *, "count :", count(big) print *, "sum(a) :", sum(a) print *, "sum masked :", sum(a, mask=big) print *, "where :", pack(a, big) end program mask

gfortran -Wall -Wextra -std=f2018 mask.f90 -o mask
./mask

a : 3 8 1 9 2 7
a > 4 : F T F T F T
any : T
all : F
count : 3
sum(a) : 30
sum masked : 24
where : 8 9 7

A logical array prints as the letters T and F without separators, one per element: six values give F T F T F T with spaces because the logical field has a width of one and the print puts a space in front of each. The three reductions answer the three questions a reader asks of a filter, and pack returns the selected values as a new array whose length is the count.

A mask in a reduction

sum(a, mask=big) is the idiom that replaces a loop with an if inside it. Every reduction takes the mask, so the mean of the values above a threshold is one expression: sum(a, mask=big) / count(big), with the count in the denominator because the divisor is the number of selected values and not the length of the array.

The zero case is the one to handle: when the mask selects nothing, the count is zero and the division is a division by zero. A program that computes a mean of a filtered set tests the count first, which is the same discipline the empty array needed in the previous lesson.

Exercises

  1. Write sum(x * y) as dot_product(x, y). Is the answer the same?
  2. Change a > 4 to a >= 4 and rebuild. Which three numbers change?
  3. Compute the mean of the values of a above 4. What does the program print, and what happens with a threshold of 100?
  4. Apply nint to a real array and print both. Which type does the result have?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does y = 2.0 * x + 1.0 do when x is an array?

    Answer

    It applies the expression to every element

    A scalar with an array is applied element by element.

  2. What does sqrt(x) return for an array x?

    Answer

    An array of the same shape with the square root of each element

    sqrt is elemental, so it maps over the array.

  3. What is a > 4 for an integer array?

    Answer

    A logical array of the same shape

    An array compared with a scalar gives an array of logicals, a mask.

  4. What does count(big) return for a mask?

    Answer

    The number of true elements

    count counts the elements that satisfy the mask.

  5. What does this program print? program p implicit none integer :: a(3) a = [1, 2, 3] print *, sum(a, mask=a > 1) end program p

    Answer

    5

    The mask selects 2 and 3, and their sum is 5.

  6. What does pack(a, big) return?

    Answer

    A new array of the selected values

    pack gathers the elements where the mask is true.

  7. What must a program check before dividing by count(mask)?

    Answer

    That the count is not zero

    A mask that selects nothing gives a zero divisor.

  8. Which reduction gives the largest element?

    Answer

    maxval

    maxval returns the value; maxloc returns its position.

  9. Which intrinsic returns the position of the smallest element?

    Answer

    minloc

    minloc gives the index; minval gives the value.

  10. Why does the whole-array form matter for performance?

    Answer

    The compiler sees the loop and can vectorise it without proving the source loop is independent

    The form is a statement about the whole array, which the optimiser can map to vector instructions.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev