Fortran Array Reductions
Fortran has a rich library of built-in intrinsic functions that work on whole arrays. Reductions turn an array into a single value (or one value per row/column): sums, products, extremes, counts and tests. They replace most of the small loops you would otherwise write.
Sum, product, minimum and maximum
program reductions
implicit none
integer :: sales(7) = [120, 95, 143, 88, 160, 210, 175] ! Mon..Sun
print '(a, i0)', 'total sales: ', sum(sales)
print '(a, f0.1)', 'daily average: ', real(sum(sales)) / size(sales)
print '(a, i0)', 'best day: ', maxval(sales)
print '(a, i0)', 'worst day: ', minval(sales)
print '(a, i0)', 'best day index: ', maxloc(sales, dim=1)
print '(a, i0)', 'worst day index:', minloc(sales, dim=1)
print '(a, i0)', 'product of 1..10: ', product([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
end program reductionstotal sales: 991
daily average: 141.6
best day: 210
worst day: 88
best day index: 6
worst day index:4
product of 1..10: 3628800
maxloc and minloc return the position of the extreme value. Without dim=1 they return an array with one index per dimension (even for a 1-D array, an array of size 1), so dim=1 is the convenient form for vectors. If the extreme occurs more than once, the first position is returned.
Logical reductions: any, all, count
These take a logical array, usually built with a comparison on the whole array:
program logical_reductions
implicit none
real :: temps(6) = [18.5, 22.0, 31.2, 29.8, 35.1, 24.4]
print '(a, l1)', 'any above 35? ', any(temps > 35.0)
print '(a, l1)', 'all above 15? ', all(temps > 15.0)
print '(a, i0)', 'days above 25: ', count(temps > 25.0)
print '(a, 6l2)', 'mask: ', temps > 25.0
end program logical_reductionsany above 35? T
all above 15? T
days above 25: 3
mask: F F T T T F
The mask argument
Most reductions accept an optional mask: only the elements where the mask is true take part. This answers questions like "the sum of the positive values" without a loop:
program masked
implicit none
real :: changes(8) = [12.5, -3.0, 7.25, -8.5, 0.0, 4.0, -1.25, 9.0]
print '(a, f7.2)', 'gains: ', sum(changes, mask=changes > 0.0)
print '(a, f7.2)', 'losses: ', sum(changes, mask=changes < 0.0)
print '(a, f7.2)', 'largest loss: ', minval(changes, mask=changes < 0.0)
print '(a, f7.2)', 'smallest gain:', minval(changes, mask=changes > 0.0)
print '(a, i0)', 'first loss at index ', findloc(changes < 0.0, .true., dim=1)
end program maskedgains: 32.75
losses: -12.75
largest loss: -8.50
smallest gain: 4.00
first loss at index 2
findloc(array, value, dim=1) (Fortran 2008) returns the first position where array equals value, or 0 if it doesn't occur.
Reducing along one dimension
For a matrix, dim=1 reduces down each column and dim=2 across each row; the result is a vector:
program by_dimension
implicit none
! rows = students, columns = 3 exams
integer :: marks(4, 3)
integer :: s
marks = reshape([70, 85, 62, 90, & ! exam 1 (column 1)
75, 80, 58, 95, & ! exam 2
68, 92, 71, 88], & ! exam 3
[4, 3])
print '(a, 3i5)', 'exam totals: ', sum(marks, dim=1)
print '(a, 3i5)', 'exam best: ', maxval(marks, dim=1)
print '(a, 4i5)', 'student sums: ', sum(marks, dim=2)
do s = 1, 4
print '(a, i0, a, f5.1)', 'student ', s, ' average: ', sum(marks(s, :)) / 3.0
end do
print '(a, 2i3)', 'location of the top mark (row, col):', maxloc(marks)
end program by_dimensionexam totals: 307 308 319
exam best: 90 95 92
student sums: 213 257 191 273
student 1 average: 71.0
student 2 average: 85.7
student 3 average: 63.7
student 4 average: 91.0
location of the top mark (row, col): 4 2
More array intrinsics
| Function | Result |
|---|---|
size(a [, dim]), shape(a), lbound, ubound |
sizes and bounds |
sum, product, maxval, minval |
reductions (dim, mask optional) |
maxloc, minloc, findloc |
positions |
any, all, count |
logical reductions |
merge(tsource, fsource, mask) |
element-wise choice between two values |
pack(a, mask) |
a 1-D array of the elements where mask is true |
cshift(a, shift), eoshift(a, shift) |
circular / end-off shifts |
norm2(a) |
Euclidean norm √(Σ aᵢ²) |
program pack_merge
implicit none
integer :: i
integer :: n(10) = [(i, i = 1, 10)]
print '(*(i3))', pack(n, mod(n, 3) == 0) ! multiples of 3
print '(*(i3))', merge(n, -n, mod(n, 2) == 0) ! keep evens, negate odds
print '(*(i3))', cshift(n, 3) ! rotate left by 3
print '(f8.4)', norm2([3.0, 4.0, 12.0])
end program pack_merge 3 6 9
-1 2 -3 4 -5 6 -7 8 -9 10
4 5 6 7 8 9 10 1 2 3
13.0000
Test yourself
What does count(x > 0) return?
- The sum of the positive elements
- The number of positive elements
- The index of the first positive element
- A logical array
For a matrix m, what does sum(m, dim=1) produce?
- The total of all elements
- One sum per column
- One sum per row
- The diagonal sum
How do you sum only the negative elements of v?
sum(v < 0)sum(v, mask=v < 0)sum(v) - sum(abs(v))minval(v)