Arrays as first-class objects
In Fortran an array is a first-class object: it is declared, assigned, sliced, and passed to procedures as a unit, in much the same way as a scalar. Arrays may be fixed-size or allocatable:
real :: temperatures(365) ! fixed size
real, allocatable :: grid(:,:) ! size set later
allocate(grid(100,100))Whole-array expressions
A whole-array expression operates on every element at once, which is both clearer and easier for compilers to optimize than an explicit loop. The two statements below are equivalent:
do i = 1, n
y(i) = sin(x(i))
end do
y = sin(x) ! same result, whole-array formCommon intrinsic functions
The language ships with a large set of intrinsic functions; the array-related ones do the most work in scientific code:
- sum — the sum of an array's elements.
- product — the product of an array's elements.
- maxval and minval — the largest and smallest elements.
- dot_product — the dot product of two rank-one arrays.
- matmul — matrix multiplication of two rank-two arrays.
- transpose, size, shape — shape and layout inquiries.
A compact example:
program array_sum
implicit none
real :: a(5)
a = [1.0, 2.0, 3.0, 4.0, 5.0] ! whole-array assignment
print *, 'Total: ', sum(a)
end program array_sumArray sections
A section selects part of an array with a subscript triplet — a(2:4) is elements 2 through 4, and a(1:10:2) takes every second element. Sections can be assigned, passed to procedures, and used in expressions. To copy a section into a separate variable, assign it to an allocatable array, which takes the correct size automatically:
real, allocatable :: part(:)
part = data(500:999)The Fortran Intrinsics Quick Reference lists the most-used intrinsics in one place.