Chuyển đến nội dung

Bài 16 · Arrays and Numerics

Array Intrinsic Functions

Master Fortran's array intrinsic functions: sum, product, maxval, minloc, count, any, all, dot_product, matmul, transpose, pack, spread, cshift and the dim and mask arguments.

Fortran ships with a rich library of functions that take a whole array and return a single answer, or a new array. Many programs that need a loop in other languages become a one-liner here. This lesson tours the most useful intrinsics, shows the dim and mask arguments, and ends with a few realistic examples.

Reductions: one answer from many

Function Result
sum(a) sum of all elements
product(a) product of all elements
maxval(a) / minval(a) largest / smallest element
maxloc(a) / minloc(a) position of the largest / smallest, as an array
count(mask) how many elements of a logical array are true
any(mask) / all(mask) is at least one / is every element true
size(a) number of elements
norm2(a) Euclidean length (Fortran 2008)
dot_product(a, b) sum of a(i) * b(i)
FORTRAN
program reductions
  implicit none
  real :: a(5) = [3.0, 8.0, 1.0, 9.0, 4.0]

  print *, sum(a)               ! 25
  print *, sum(a) / size(a)     ! mean: 5
  print *, maxval(a), minval(a) ! 9 and 1
  print *, maxloc(a)            ! 4  (as a one-element array)
  print *, count(a > 3.0)       ! 3
  print *, any(a > 8.5), all(a > 0.0)    ! T T
  print *, dot_product(a, a)    ! 171
end program reductions

Notice that maxloc returns an array (one index per dimension). For a 1D array that is one number, and you take it with maxloc(a, dim=1) to get a scalar, or just maxloc(a, 1). Positions count from the array's lower bound... almost: maxloc of an array declared a(0:4) still reports 1 for the first element, since positions are relative to the start of the array. Remember this when your bounds do not start at 1.

Python Stand-in (Python): reductions

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.

The dim argument

For a matrix, sum(m) adds everything. Add dim= to reduce along one dimension and get an array back:

FORTRAN
integer :: m(2, 3) = reshape([1, 2, 3, 4, 5, 6], [2, 3])
! m = | 1 3 5 |
!     | 2 4 6 |

print *, sum(m)             ! 21
print *, sum(m, dim=1)      ! 3 7 11   sum down each column
print *, sum(m, dim=2)      ! 9 12     sum across each row
print *, maxval(m, dim=2)   ! 5 6

dim=1 collapses the first index: you get one value per column. This surprises people who think of it as "sum by row". Work it out: the first dimension disappears.

Python Stand-in (Python): dim=1 and dim=2

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.

The mask argument

Most reductions accept mask=, a logical array of the same shape; only elements where the mask is true take part:

FORTRAN
real :: t(6) = [12.0, -3.0, 25.0, 7.0, -8.0, 30.0]

print *, sum(t, mask=t > 0.0)           ! 74: sum of positives
print *, count(t < 0.0)                 ! 2 negatives
print *, maxval(t, mask=t < 20.0)       ! 12
print *, minval(t, mask=t > 0.0)        ! 7

If the mask selects nothing, sum is 0 and product is 1; maxval gives the most negative number of the type.

Matrices: matmul and transpose

matmul(a, b) multiplies matrices (rows times columns). transpose(m) swaps rows and columns:

FORTRAN
real :: a(2, 2) = reshape([1, 3, 2, 4], [2, 2])     ! | 1 2 |
real :: b(2, 2) = reshape([0, 1, 1, 0], [2, 2])     ! | 3 4 |  and | 0 1 | swap matrix
real :: c(2, 2)                                      !              | 1 0 |

c = matmul(a, b)        ! | 2 1 |
                        ! | 4 3 |   (columns of a swapped)

matmul also handles matrix-vector products, matmul(a, x). For large matrices the compiler can call a fast library (BLAS) behind the scenes. dot_product(x, y) is the vector special case.

Python Stand-in (Python): matmul, transpose, dot product

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.

Building and rearranging arrays

Function Purpose Example
reshape(a, shape) change shape reshape(v, [3, 4])
spread(a, dim, n) repeat along a new dimension spread([1,2,3], 1, 2) gives 2 rows
merge(t, f, mask) choose elementwise merge(a, 0.0, a > 0.0)
pack(a, mask) gather selected elements into a vector pack(a, a > 0)
unpack(v, mask, field) scatter a vector back
cshift(a, k) circular shift cshift([1,2,3,4], 1) = [2,3,4,1]
eoshift(a, k) end-off shift, filling with zero eoshift([1,2,3,4], 1) = [2,3,4,0]
product, iall, iany bitwise or product reductions

pack with a mask is the Fortran way to filter. merge is an elementwise conditional (like the ternary operator): merge(x, y, cond) takes x where cond is true and y otherwise, so abs_a = merge(a, -a, a >= 0.0) is a one-line absolute value.

Python Stand-in (Python): pack, merge, cshift, eoshift

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.

A worked example: statistics in four lines

FORTRAN
program stats
  implicit none
  real :: x(8) = [4.0, 8.0, 15.0, 16.0, 23.0, 42.0, 5.0, 9.0]
  real :: mean, var

  mean = sum(x) / size(x)
  var  = sum((x - mean) ** 2) / (size(x) - 1)
  print *, "mean =", mean
  print *, "sd   =", sqrt(var)
  print *, "range:", minval(x), "to", maxval(x)
end program stats

The mean is 15.25; the variance and standard deviation come from the same array expressions. (x - mean) ** 2 is an array of squared deviations, and sum collapses it. There is not a single loop.

Python Stand-in (Python): the statistics example

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.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which call returns the sum of each column of a matrix m?

    dim=1 collapses the first (row) index, leaving one sum per column.
  2. 2. What does count(a > 3.0) return?

    count counts the true elements of a logical array.
  3. 3. What does merge(a, 0.0, a > 0.0) compute?

    merge chooses the first argument where the mask is true and the second elsewhere, keeping the shape.
  4. 4. What does pack(a, a > 0.0) return?

    pack gathers the selected elements into a shorter vector.

Summary

  • Reductions such as sum, product, maxval, minval, count, any and all replace loops.
  • dim= reduces along one dimension; mask= limits which elements take part.
  • maxloc/minloc return positions as arrays, relative to the array start.
  • matmul, transpose and dot_product do linear algebra; reshape, spread, merge, pack, cshift rearrange data.
  • Array expressions like sum((x - mean) ** 2) give statistics without a loop.

Next: where and Masking

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.