Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Arrays and Numerics

where and Masking

Apply operations only to selected array elements with where, elsewhere, masked assignment, merge, pack and unpack, and learn why forall gave way to do concurrent.

Whole-array arithmetic is great until you need a condition: "double the positive elements, zero the negative ones". A loop with an if works, but Fortran gives you a loop-free tool, masked array assignment with where. A mask is a logical array of the same shape as the data; the operation is applied only where the mask is true.

The where statement

The one-line form takes a mask and a single assignment:

FORTRAN
where (a < 0.0) a = 0.0           ! clamp negatives to zero
where (b /= 0.0) c = a / b        ! divide only where it is safe

The mask a < 0.0 is itself an array of logicals, one per element. Only the elements with a true mask are assigned. This also protects from errors: elements where b == 0.0 are never divided.

The where construct

For several statements and an alternative, use the block form with elsewhere:

FORTRAN
program where_demo
  implicit none
  real :: t(6) = [12.0, -3.0, 25.0, 7.0, -8.0, 30.0]
  real :: out(6)

  where (t > 0.0)
    out = sqrt(t)
  elsewhere
    out = 0.0
  end where
  print "(6F7.3)", out
end program where_demo

For this data the printed row is:

TEXT
  3.464  0.000  5.000  2.646  0.000  5.477

Since sqrt of a negative would be an error or NaN, the mask keeps it away from the negative elements. You can chain masks:

FORTRAN
where (score >= 90)
  grade = "A"
elsewhere (score >= 80)
  grade = "B"
elsewhere (score >= 70)
  grade = "C"
elsewhere
  grade = "F"
end where

where works like an if ladder, one pass per branch, evaluated array-wide.

flowchart TD
  A["mask = t > 0"] --> B["where: out = sqrt(t)"]
  A --> C["elsewhere: out = 0"]
  B --> D["combined result array"]
  C --> D

The mask is computed once up front; each branch only touches its own elements.

Python Stand-in (Python): where / elsewhere

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rules of where

  • Every assignment inside where must be an array assignment with the same shape as the mask.
  • The mask is evaluated once, before any assignment. Changing the array inside the construct does not change which elements are selected.
  • Only elemental functions can appear on the right, and they are applied elementwise.
  • You cannot jump out of a where or call non-elemental procedures with side effects.
  • Since Fortran 2008, a where can be nested and can have a mask-expression on the first elsewhere.

The "mask evaluated once" rule is useful: in where (a > 0) a = -a no element is processed twice, which a naive loop with changing values might do.

merge: masking inside an expression

where is a statement; merge(tsource, fsource, mask) is a function, so it fits inside larger expressions:

FORTRAN
signs  = merge(1.0, -1.0, x >= 0.0)         ! +1 or -1 for each element
safe   = a / merge(b, 1.0, b /= 0.0)        ! replace zero divisors by 1
clamped = max(min(x, hi), lo)               ! no mask needed for simple clamps

When the result is one value per element and you need it inside another formula, prefer merge. For multi-statement blocks, where reads better.

Masks in reductions

Mask arguments to sum, count, maxval and friends (see array intrinsic functions) follow the same idea:

FORTRAN
real :: x(8)
print *, sum(x, mask=x > 0.0) / count(x > 0.0)    ! mean of the positives

If no element is positive the division is zero by zero, so guard it with if (any(x > 0.0)).

Python Stand-in (Python): mean of the positives with a guard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

pack and unpack: gather and scatter

pack copies the selected elements into a compact vector, and unpack puts a vector back into the positions marked by a mask:

FORTRAN
real :: a(5) = [3.0, -1.0, 4.0, -1.5, 5.0]
real, allocatable :: pos(:)

pos = pack(a, a > 0.0)                  ! [3.0, 4.0, 5.0]
pos = pos * 10.0                        ! work on the compact copy
a = unpack(pos, a > 0.0, a)             ! put back; others keep their old values
! a is now [30.0, -1.0, 40.0, -1.5, 50.0]

The three-argument unpack(vector, mask, field) takes field for positions where the mask is false. This pattern (extract, process densely, write back) is common for sparse updates.

Python Stand-in (Python): pack, process, unpack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

forall and do concurrent

forall (Fortran 95) assigns array elements by index expression:

FORTRAN
forall (i = 1:n, j = 1:n) m(i, j) = 1.0 / real(i + j - 1)

It was meant to help parallel compilers, but it proved hard to optimize, and the 2018 standard marks it obsolescent. Use do concurrent (covered in the parallel chapter) or ordinary loops and array syntax. You will still read forall in older code: it is "a loop whose iterations may run in any order, with a mask", nothing more.

Choosing the right tool

Task Best tool
Different formulas for different elements, several statements where ... elsewhere
A value choice inside an expression merge
A mask for a sum, count or maximum mask= argument
Filter to a shorter vector pack
Index-dependent formula do concurrent or a loop

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

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

    The mask a < 0.0 selects all the negative elements, and only those are assigned.
  2. 2. When is the mask of a where construct evaluated?

    The mask is computed once, so assignments inside the construct do not change which elements are selected.
  3. 3. What is merge(1.0, -1.0, x >= 0.0)?

    merge picks the first value where the mask is true and the second elsewhere, elementwise.
  4. 4. What replaced forall in modern Fortran?

    forall is obsolescent; do concurrent expresses independent iterations.

Summary

  • where (mask) assignment applies an array assignment only where the mask is true.
  • The construct form has elsewhere branches and evaluates the mask once.
  • merge(t, f, mask) is the function form for use inside expressions.
  • pack gathers selected elements, unpack scatters them back; mask= limits reductions.
  • forall is obsolescent: prefer do concurrent, where or loops.

Next: Allocatable Arrays