Whole-array arithmetic in Fortran
Elementwise math on entire arrays with not a loop in sight.
program vector_ops
implicit none
real :: raw(5) = [12.5, 8.0, 15.25, 6.75, 11.0]
real :: net(5)
! Arithmetic on whole arrays, elementwise, no loop written.
net = raw * 0.9
print *, "net weights: ", net
print *, "over 7 lbs: ", net > 7.0
! Two arrays combine element by element the same way.
print *, "difference: ", raw - net
end program vector_ops
How it works
net = raw * 0.9scales every element in one statement.net > 7.0is an array of logicals, printed as T and F.raw - netcombines two arrays element by element, same shape in, same shape out.
Keywords and builtins used here
endimplicitnoneprintprogramreal
The run, in numbers
- Lines
- 12
- Characters to type
- 351
- Tokens
- 60
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 55 seconds.
Step 1 of 3 in Whole-array thinking, step 10 of 27 in Language basics.