Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Arrays and Numerics

Array Sections and Whole-Array Operations

Slice Fortran arrays with start:end:stride sections, operate on whole arrays without loops, use elemental functions, row and column sections of matrices and vector subscripts.

The feature that makes Fortran code short is array syntax: you can treat an array, or any slice of it, as a single value. a = b + c adds two arrays element by element with no loop. A slice such as a(2:5) picks part of an array and can appear on either side of an assignment. This lesson explains sections, whole-array arithmetic, conformability and elemental functions.

Whole-array operations

If arrays have the same shape, they can be combined with any operator:

FORTRAN
program whole_array
  implicit none
  real :: a(4) = [1.0, 2.0, 3.0, 4.0]
  real :: b(4) = [10.0, 20.0, 30.0, 40.0]
  real :: c(4)

  c = a + b          ! 11 22 33 44
  c = a * b          ! 10 40 90 160
  c = 2.0 * a + 1.0  ! 3 5 7 9
  c = a ** 2         ! 1 4 9 16
  print *, c
end program whole_array

Operations apply element by element ("elementwise"). A scalar is broadcast: 2.0 * a multiplies every element. Note that a * b is not a matrix product; for that use matmul (next lesson).

Two arrays are conformable if they have the same shape (or one is a scalar). Adding a 4-element array to a 5-element array is a compile-time error when the compiler can see the sizes.

The right-hand side is evaluated completely before the assignment, so a = a(4:1:-1) reverses an array correctly without a temporary you declare.

Python Stand-in (Python): elementwise operations and broadcasting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Sections

A section is a(start:stop:stride). Each part is optional and defaults to the array's own bounds and stride 1. Both ends are included:

FORTRAN
real :: a(10) = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]

print *, a(3:6)       ! 3 4 5 6
print *, a(:4)        ! 1 2 3 4
print *, a(7:)        ! 7 8 9 10
print *, a(::2)       ! 1 3 5 7 9
print *, a(10:1:-3)   ! 10 7 4 1
print *, a(5)         ! 5       (a single element, not a section)

Printed with list-directed output the values look like 3.00000000; the lists above show just the numbers. Sections can be assigned to as well:

FORTRAN
a(1:3) = 0.0            ! first three become 0
a(2:10:2) = a(1:9:2)    ! shift copies; the right side is evaluated first
a(:) = a(10:1:-1)       ! reverse the whole array

A section like a(2:5) has a size of 4 and its own lower bound of 1, if you pass it to a procedure with an assumed-shape dummy argument.

Python Stand-in (Python): Fortran sections, 1-based and inclusive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Sections of matrices

For a 2D array, each dimension has its own section. A single index fixes a row or a column; a colon : takes everything:

FORTRAN
integer :: m(3, 4)
m = reshape([(i, i = 1, 12)], [3, 4])
! m = | 1 4 7 10 |
!     | 2 5 8 11 |
!     | 3 6 9 12 |

print *, m(2, :)       ! row 2:    2 5 8 11
print *, m(:, 3)       ! column 3: 7 8 9
print *, m(2:3, 2:3)   ! a 2x2 block: 5 8 6 9  (printed column by column)
m(1, :) = 0            ! zero out the first row
m(:, 1) = [7, 8, 9]    ! set the first column

Printing a whole 2D array walks column by column (the memory order). To print row by row, loop over the rows: do i = 1, 3; print "(4I4)", m(i, :); end do.

flowchart TD
  A["m(3,4)"] --> B["m(2,:) one row"]
  A --> C["m(:,3) one column"]
  A --> D["m(2:3,2:3) a block"]

Fixing an index drops a dimension: a row or column of a matrix is a 1D array.

Elemental intrinsic functions

Most math functions are elemental: given an array, they apply to every element and return an array of the same shape:

FORTRAN
real :: x(3) = [0.0, 1.0, 4.0]
print *, sqrt(x)          ! 0, 1, 2
print *, exp(-x)          ! e to the minus each
print *, abs([-3, 2, -1]) ! 3 2 1
print *, max(x, 2.0)      ! 2 2 4   (compares each with 2.0)

You can also write your own elemental procedures; they are in the procedures chapter. This is how you replace most loops over numbers.

Python Stand-in (Python): elemental functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Vector subscripts

An integer array can be used as an index to pick arbitrary elements, in any order, with repeats on read:

FORTRAN
integer :: idx(3) = [5, 1, 3]
real :: a(5) = [10.0, 20.0, 30.0, 40.0, 50.0]

print *, a(idx)          ! 50 10 30
a(idx) = 0.0             ! legal: no repeated index

Assigning through a vector subscript with a repeated index (like [1, 1]) is not allowed, since the result would be ambiguous. Vector subscripts are the Fortran version of "fancy indexing".

Common mistakes

  • Non-conformable shapes. c(5) = a(4) + b(5) fails; check with size or shape.
  • Confusing * with matrix multiplication. Elementwise product is *; matrix product is matmul.
  • Forgetting that the section is inclusive. a(1:3) has three elements.
  • Overlap surprises. Because the right side is fully evaluated first, a(2:5) = a(1:4) shifts correctly. The same in a hand-written loop would smear the first value across.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which elements does a(2:8:3) select from an array of 10?

    Start at 2, step by 3 up to and including 8: indices 2, 5 and 8.
  2. 2. What does c = a * b do for two real arrays of the same shape?

    • works element by element; matmul performs matrix multiplication.
  3. 3. Which expression is the third column of a 3x4 matrix m?

    m(:, 3) fixes the second index (the column) and takes every row.
  4. 4. What is sqrt([1.0, 4.0, 9.0])?

    sqrt is elemental, so it applies to each element and returns an array of the same shape.

Summary

  • Arrays of the same shape combine elementwise; scalars broadcast to every element.
  • A section a(start:stop:stride) is inclusive, with defaults for each part; negative strides reverse.
  • m(i, :) is a row and m(:, j) a column; a fixed index removes a dimension.
  • Elemental intrinsics such as sqrt, exp, abs and max work on whole arrays.
  • Vector subscripts pick arbitrary elements; the right side is evaluated before assignment.

Next: Array Intrinsic Functions