Numerics
Elemental Functions
Apply Per Element
An elemental function works on a scalar but can be applied element-wise to a whole array.
Program
Play the program to double every element of an array.
elemental.f90
Replay: real traced execution (multi-file project)
program elemental_demo
implicit none
integer :: nums(4), doubled(4)
nums = [1, 2, 3, 4]
doubled = times_two(nums)
print '(I0)', sum(doubled)
contains
elemental function times_two(x) result(y)
integer, intent(in) :: x
integer :: y
y = x * 2
end function times_two
end program elemental_demo
nums ← [1, 2, 3, 4]
3integer :: nums(4), doubled(4)4nums = [1, 2, 3, 4]5doubled = times_two(nums)values this step[1, 2, 3, 4]numsdoubled ← [2, 4, 6, 8]
4nums = [1, 2, 3, 4]5doubled = times_two(nums)6print '(I0)', sum(doubled)values this step[2, 4, 6, 8]doubled[1, 2, 3, 4]numsprint '(I0)', sum(doubled)
5 doubled = times_two(nums)6 print '(I0)', sum(doubled)7containsoutput20values this step[2, 4, 6, 8]doubled
Follow the Elements
numsstarts as[1, 2, 3, 4].times_two(nums)applies the scalar function to each element.doubledbecomes[2, 4, 6, 8].sum(doubled)adds those four values.- The output is
20. | input element | doubled element | | --- | --- | | 1 | 2 | | 2 | 4 | | 3 | 6 | | 4 | 8 | | sum | 20 |
elemental
`elemental function` applies to each element of an array argument.
scalar definition
The body is written for a scalar, but works on arrays too.
intent(in)
Elemental arguments are read-only.
Exercise: elemental.f90
Reproduce the output 20, then trace how [1, 2, 3, 4] becomes [2, 4, 6, 8] before summing.