TExcelTAD
Home › Fortran › Fortran Linear Systems

Fortran Linear Systems

Solving A x = b for a vector x is the workhorse of scientific computing: finite-element models, circuit analysis, curve fitting and implicit time steppers all end up there. This lesson implements Gaussian elimination with partial pivoting, an LU factorisation, and the iterative Jacobi method, then explains when to reach for LAPACK instead.

Gaussian elimination with partial pivoting

Elimination subtracts multiples of each pivot row from the rows below it until the matrix is upper triangular, then solves by back substitution. Partial pivoting swaps in the row with the largest available pivot first, which keeps the rounding errors under control. Fortran's array sections make each step a single line:

fortran · try it yourself
module linsolve
  use iso_fortran_env, only: dp => real64
  implicit none
contains

  subroutine gauss_solve(a_in, b_in, x, info)
    real(dp), intent(in) :: a_in(:, :), b_in(:)
    real(dp), intent(out) :: x(:)
    integer, intent(out) :: info             ! 0 = ok, k > 0 = zero pivot in column k
    real(dp) :: a(size(b_in), size(b_in)), b(size(b_in)), factor, row(size(b_in)), tmp
    integer :: n, k, i, p

    a = a_in
    b = b_in
    n = size(b)
    info = 0
    do k = 1, n - 1
      p = k - 1 + maxloc(abs(a(k:n, k)), dim=1)        ! pivot row
      if (abs(a(p, k)) < tiny(1.0_dp)) then
        info = k
        return
      end if
      if (p /= k) then                                 ! swap rows k and p
        row = a(k, :); a(k, :) = a(p, :); a(p, :) = row
        tmp = b(k); b(k) = b(p); b(p) = tmp
      end if
      do i = k + 1, n
        factor = a(i, k) / a(k, k)
        a(i, k:n) = a(i, k:n) - factor * a(k, k:n)
        b(i) = b(i) - factor * b(k)
      end do
    end do
    if (abs(a(n, n)) < tiny(1.0_dp)) then
      info = n
      return
    end if
    do i = n, 1, -1                                    ! back substitution
      x(i) = (b(i) - dot_product(a(i, i+1:n), x(i+1:n))) / a(i, i)
    end do
  end subroutine gauss_solve

end module linsolve

program solve_demo
  use linsolve
  implicit none
  real(dp) :: a(3, 3), b(3), x(3)
  integer :: info

  ! 2x + y - z = 8,  -3x - y + 2z = -11,  -2x + y + 2z = -3
  a = reshape([ 2.0_dp,  1.0_dp, -1.0_dp, &
               -3.0_dp, -1.0_dp,  2.0_dp, &
               -2.0_dp,  1.0_dp,  2.0_dp], [3, 3], order=[2, 1])
  b = [8.0_dp, -11.0_dp, -3.0_dp]

  call gauss_solve(a, b, x, info)
  print '(a, i0)', 'info = ', info
  print '(a, 3f10.6)', 'x = ', x
  print '(a, es10.2)', 'residual |Ax - b| = ', norm2(matmul(a, x) - b)
end program solve_demo
info = 0
x =   2.000000  3.000000 -1.000000
residual |Ax - b| =   8.88E-16

Always check the residual ‖Ax − b‖: it tells you whether the computed x really satisfies the equations. The solution is x = 2, y = 3, z = −1.

p = k - 1 + maxloc(abs(a(k:n, k)), dim=1) deserves a closer look: maxloc on the section a(k:n, k) returns a position within the section (starting at 1), so we add k - 1 to convert it to a row index of a.

LU factorisation: solve many right-hand sides

If you have to solve with the same matrix for many vectors b, factor once into A = L·U (lower × upper triangular) and then do two cheap triangular solves per vector. Here's a compact Doolittle version without pivoting, suitable for diagonally dominant matrices such as the tridiagonal matrix of a heat-equation model:

fortran · try it yourself
module lu_mod
  use iso_fortran_env, only: dp => real64
  implicit none
contains

  subroutine lu_factor(a)                 ! overwrites a with L (below diag, unit diag implied) and U
    real(dp), intent(inout) :: a(:, :)
    integer :: k, n
    n = size(a, 1)
    do k = 1, n - 1
      a(k+1:n, k) = a(k+1:n, k) / a(k, k)
      a(k+1:n, k+1:n) = a(k+1:n, k+1:n) - matmul(a(k+1:n, k:k), a(k:k, k+1:n))
    end do
  end subroutine lu_factor

  function lu_solve(lu, b) result(x)
    real(dp), intent(in) :: lu(:, :), b(:)
    real(dp) :: x(size(b)), y(size(b))
    integer :: i, n
    n = size(b)
    do i = 1, n                           ! forward: L y = b
      y(i) = b(i) - dot_product(lu(i, 1:i-1), y(1:i-1))
    end do
    do i = n, 1, -1                       ! backward: U x = y
      x(i) = (y(i) - dot_product(lu(i, i+1:n), x(i+1:n))) / lu(i, i)
    end do
  end function lu_solve

end module lu_mod

program lu_demo
  use lu_mod
  implicit none
  integer, parameter :: n = 5
  real(dp) :: a(n, n), lu(n, n)
  integer :: i

  a = 0.0_dp                              ! tridiagonal: 4 on the diagonal, -1 beside it
  do i = 1, n
    a(i, i) = 4.0_dp
    if (i > 1) a(i, i - 1) = -1.0_dp
    if (i < n) a(i, i + 1) = -1.0_dp
  end do
  lu = a
  call lu_factor(lu)

  print '(a, 5f9.5)', 'x1 = ', lu_solve(lu, [1.0_dp, 1.0_dp, 1.0_dp, 1.0_dp, 1.0_dp])
  print '(a, 5f9.5)', 'x2 = ', lu_solve(lu, [1.0_dp, 0.0_dp, 0.0_dp, 0.0_dp, 0.0_dp])
  print '(a, es9.2)', 'check: ', norm2(matmul(a, lu_solve(lu, [1.0_dp, 2.0_dp, 3.0_dp, 4.0_dp, 5.0_dp])) &
                                    - [1.0_dp, 2.0_dp, 3.0_dp, 4.0_dp, 5.0_dp])
end program lu_demo
x1 =   0.36538  0.46154  0.48077  0.46154  0.36538
x2 =   0.26795  0.07179  0.01923  0.00513  0.00128
check:  8.88E-16

The update a(k+1:n, k+1:n) - matmul(a(k+1:n, k:k), a(k:k, k+1:n)) is an outer product of a column and a row, written with rank-2 sections (k:k keeps the dimension, unlike plain k).

Iterative methods: Jacobi

For huge sparse systems, direct elimination is too expensive, and iterative methods take over. The simplest is Jacobi iteration: solve each equation for its diagonal unknown using the previous values of the others. It converges when the matrix is diagonally dominant:

fortran · try it yourself
program jacobi_demo
  use iso_fortran_env, only: dp => real64
  implicit none
  real(dp) :: a(3, 3), b(3), x(3), x_new(3), d(3)
  integer :: iter, i

  a = reshape([10.0_dp, -1.0_dp,  2.0_dp, &
               -1.0_dp, 11.0_dp, -1.0_dp, &
                2.0_dp, -1.0_dp, 10.0_dp], [3, 3], order=[2, 1])
  b = [6.0_dp, 25.0_dp, -11.0_dp]
  d = [(a(i, i), i = 1, 3)]                    ! the diagonal

  x = 0.0_dp
  do iter = 1, 100
    x_new = (b - matmul(a, x) + d * x) / d     ! x_i = (b_i - sum_{j/=i} a_ij x_j) / a_ii
    if (maxval(abs(x_new - x)) < 1.0e-10_dp) exit
    x = x_new
  end do
  print '(a, i0, a)', 'converged after ', iter, ' iterations'
  print '(a, 3f12.8)', 'x = ', x_new
  print '(a, es9.2)', 'residual: ', norm2(matmul(a, x_new) - b)
end program jacobi_demo
converged after 19 iterations
x =   1.04326923  2.26923077 -1.08173077
residual:  1.89E-10

The whole Jacobi update is one array expression: matmul(a, x) - d * x is the off-diagonal sum for every row at once.

In practice: LAPACK

Hand-written solvers are great for learning, but production code calls LAPACK (itself written in Fortran), which is heavily optimised and handles pivoting, conditioning and special matrix structures:

fortran
! solve A x = b with LAPACK's dgesv; link with -llapack -lblas (or OpenBLAS / MKL)
integer :: ipiv(n), info
call dgesv(n, 1, a, n, ipiv, b, n, info)   ! on exit, b holds the solution
if (info /= 0) error stop 'dgesv failed'

LAPACK routine names encode the precision (d = double), the matrix type (ge = general, po = positive definite, gt = tridiagonal) and the task (sv = solve, trf = factor, ev = eigenvalues).

Test yourself

Why is partial pivoting used in Gaussian elimination?

  1. To save memory
  2. To avoid dividing by small pivots, which amplifies rounding errors
  3. To make the matrix symmetric
  4. It is required for integer matrices

What is the advantage of an LU factorisation when solving for many right-hand sides?

  1. It is more accurate
  2. The expensive factorisation is done once; each extra solve is only two triangular substitutions
  3. It doesn't need back substitution
  4. It works only for one b

What does maxloc(abs(a(k:n, k)), dim=1) return?

  1. The largest value
  2. The row index within the section, counting from 1
  3. The row index in the full matrix
  4. The column index