WHERE and ELSEWHERE

An if chooses between statements; where chooses between assignments, element by element, over a whole array at once. It is the array form of an if and the natural companion of the masks of the whole-array lesson: the same comparison that made a mask in a reduction can decide which elements a statement writes. This lesson writes a masked assignment, adds branches, and shows the copy rule that makes the construct reliable when the mask and the data are the same array.

A masked assignment

where (x < 0.0) ... end where is a block in which every assignment happens only for the elements where the mask is true. The rest of the array keeps its old values, which is the difference from a plain assignment: there the statement writes every element.

The file where.f90:

program where_demo implicit none integer, parameter :: n = 6 real :: x(n), y(n) x = [-2.0, 4.0, -1.0, 9.0, -3.0, 0.0] y = x where (x < 0.0) y = 0.0 end where print *, "x :", x print *, "y :", y end program where_demo

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

x : -2.00000000 4.00000000 -1.00000000 9.00000000 -3.00000000 0.00000000
y : 0.00000000 4.00000000 0.00000000 9.00000000 0.00000000 0.00000000

Three elements were negative and became zero; the other three kept the value they had. The mask is an array of logicals of the same shape as x, exactly the value the comparison gives on its own, and a mask of the wrong shape is a compile error rather than a silent truncation.

WHERE with ELSEWHERE

The construct takes elsewhere, with or without a mask, the way an if takes else if: the branches are tried in order and each element takes the first one whose mask is true. A final elsewhere without a mask catches every element the earlier masks left alone.

The file elsewhere.f90:

program band_demo implicit none integer, parameter :: n = 6 real :: t(n), band(n) t = [-5.0, 0.0, 12.5, 30.0, -0.5, 100.0] where (t < 0.0) band = -1.0 elsewhere (t < 20.0) band = 0.0 elsewhere band = 1.0 end where print *, "t :", t print *, "band :", band end program band_demo

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

t : -5.00000000 0.00000000 12.5000000 30.0000000 -0.500000000 100.000000
band : -1.00000000 0.00000000 0.00000000 1.00000000 -1.00000000 1.00000000

Six values fall into three bands and the output is a single classification, written without a loop and without an if per element. A branch mask is a full mask of the array: the second elsewhere tests every element, and only the elements the first branch did not claim are affected, because the branches are exclusive by definition and not by the shape of the masks.

The mask is evaluated once

The mask and the right-hand sides are values, taken before any element is written. That matters when the mask and the assignment read the same array: the construct is defined on the original contents, not on the contents as they change element by element.

The file once.f90 runs the same operation twice, once as a WHERE and once as a loop that reads the array it has already modified:

program once_demo implicit none integer :: a(5), b(5), i a = [5, 1, 4, 2, 3] b = a where (a(2:5) < a(1:4)) a(2:5) = a(1:4) do i = 2, 5 if (b(i) < b(i - 1)) b(i) = b(i - 1) end do print *, "where :", a print *, "loop :", b end program once_demo

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

where : 5 5 4 4 3
loop : 5 5 5 5 5

The single-line where is the whole construct on one line, allowed when it holds one assignment and no elsewhere. Its mask compares the array with a shifted copy of itself, and the copy is what the right side uses, so the result is 5 5 4 4 3: element two was raised, element three was compared with the original element two and stayed, element four was raised. The loop is a running maximum and gives 5 5 5 5 5, because each comparison sees what the previous step wrote.

Both answers are correct for the question each one asks. The comparison is the argument for the construct: the WHERE form says what a reader means (take the larger of each adjacent pair, all at once), and the loop says what a machine does when it walks the array in order.

Masks on a grid

The construct is not limited to rank one. A mask over a rank-2 array selects cells, and the values are written in memory order, which is column by column: the first index moves fastest, as the indexing lesson showed with a matrix built by reshape.

The file grid.f90 clips a field at zero and then asks two questions about what is left:

program grid_demo implicit none integer, parameter :: nx = 4, ny = 3 real :: field(nx, ny) field = reshape([-1.0, 2.0, 3.0, -4.0, 5.0, -6.0, 7.0, 8.0, -9.0, 10.0, 11.0, 12.0], & [nx, ny]) where (field < 0.0) field = 0.0 end where print *, "field :", field print *, "hot :", count(field > 5.0) print *, "max :", maxval(field, mask=field < 6.0) end program grid_demo

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

field : 0.00000000 2.00000000 3.00000000 0.00000000 5.00000000 0.00000000 7.00000000 8.00000000 0.00000000 10.0000000 11.0000000 12.0000000
hot : 5
max : 5.00000000

The & at the end of a line continues the statement on the next one, and it must be the last character of the line; the continuation of a list-directed print then shows all twelve values in memory order. Three of them became zero, five are above five, and the largest value under six is five.

A mask in a reduction

maxval(field, mask=field < 6.0) is the reduction with a filter, the same keyword the whole-array lesson used with sum. The pair of functions is the whole numerical idiom: clip with a WHERE, count with count, and reduce with a mask. Every reduction in the language accepts the keyword, and pack turns the mask into the selected values when a program needs them as an array.

One rule to keep: a mask that selects no element gives the identity value for maxval and minval (the largest and smallest number of the type) and zero for count, and a division by that count is still a division by zero. A filter is only safe to divide by once its count has been tested.

Exercises

  1. Change the mask of where.f90 to x < 4.0 and rebuild. Which elements change now?
  2. Add an elsewhere branch to the first program that doubles the positive values. What does the output look like?
  3. Replace the single-line WHERE of once.f90 with a block form over the whole array: where (a < a(1)) a = a(1). Is the result the same as the loop?
  4. Print count(field < 0.0) before the WHERE and after it. Why are the two numbers different?

Questions

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

  1. What does where (x < 0.0) y = 0.0 do?

    Answer

    Sets y to zero where x is negative and leaves the other elements alone

    WHERE is a masked assignment: only the elements the mask selects are written.

  2. What does a mask have to be?

    Answer

    A logical array of the same shape as the array being assigned

    The mask selects element by element, so its shape must conform.

  3. What does this program print? program p implicit none integer :: a(4) a = [1, -2, 3, -4] where (a < 0) a = 0 print *, sum(a) end program p

    Answer

    4

    The two negative values become zero, so 1 + 0 + 3 + 0 is 4.

  4. How many branches may a block WHERE have?

    Answer

    One WHERE and any number of ELSEWHERE branches

    The construct is one WHERE followed by zero or more ELSEWHERE blocks.

  5. What does a final elsewhere without a mask select?

    Answer

    Every element the earlier masks did not select

    It is the default branch, like ELSE in an IF construct.

  6. When is the mask of a WHERE evaluated?

    Answer

    Once, before any element is assigned

    The construct works on values, so the mask and the right sides are taken first.

  7. The WHERE form and a loop over the same array can differ. Why?

    Answer

    The WHERE sees the original array, the loop sees what it has already written

    The construct is defined on copies; a loop reads the array as it stands.

  8. What does count(field > 5.0) return?

    Answer

    The number of elements above five

    count counts the true elements of a mask.

  9. What is maxval(a, mask=a < 6.0)?

    Answer

    The largest element of a that is below six

    The mask removes the elements that do not qualify before the reduction.

  10. What must a program do before dividing by a count taken from a mask?

    Answer

    Test that the count is not zero

    A mask that selects nothing leaves a zero divisor.

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