Array Operations & Intrinsics
11.1 Reduction & inquiry intrinsics
integer :: a(3, 4)
a = reshape([(i, i = 1, 12)], [3, 4])
print *, size(a), size(a, 1), size(a, dim=2), shape(a), lbound(a), ubound(a)
print *, sum(a), sum(a, dim=1), sum(a, mask=a > 5)
print *, product([1, 2, 3, 4])
print *, maxval(a), minval(a), maxloc(a), minloc(a, dim=2)
print *, count(a > 6), any(a == 7), all(a > 0)
print *, findloc([3, 7, 9, 7], 7) ! [2] (F2008)
print *, norm2([3.0, 4.0]) ! 5.0
print *, iall([7, 3]), iany([1, 2]), parity([.true., .false.])
11.2 Construction & manipulation
reshape(source, shape [, pad, order])
transpose(m)
matmul(A, B) ! matrix product
dot_product(u, v)
spread([1, 2, 3], dim=2, ncopies=2) ! replicate along a new dimension
pack(a, mask=a > 5) ! select elements into a 1-D array
unpack(v, mask, field)
merge(tsource, fsource, mask) ! element-wise choice: merge(1, 0, x > 0)
cshift(v, shift=1) ! circular shift
eoshift(v, shift=1, boundary=0) ! end-off shift
11.3 WHERE construct
where (a > 0.0)
b = log(a)
elsewhere (a == 0.0)
b = -huge(1.0)
elsewhere
b = 0.0
end where
11.4 FORALL (obsolescent) and DO CONCURRENT
forall (i = 1:n, j = 1:n, i /= j) a(i, j) = 1.0 / real(i - j) ! obsolescent in F2018
do concurrent (i = 1:n, j = 1:m, a(i, j) > 0) ! iterations independent → can parallelize/vectorize
b(i, j) = sqrt(a(i, j))
end do
11.5 Linear algebra example
program linalg
implicit none
integer, parameter :: dp = kind(1.0d0)
real(dp) :: A(3, 3), x(3), b(3)
integer :: i
A = reshape([2.0_dp, 1.0_dp, 0.0_dp, &
1.0_dp, 3.0_dp, 1.0_dp, &
0.0_dp, 1.0_dp, 4.0_dp], [3, 3])
x = [1.0_dp, 2.0_dp, 3.0_dp]
b = matmul(A, x)
print '(3f10.4)', b
print '(3f10.4)', transpose(A)
print *, "trace =", sum([(A(i, i), i = 1, 3)])
end program linalg