matrix_determinant Function

public pure recursive function matrix_determinant(n, a) result(det)

Matrix determinant of an matrix (recursive formulation).

Reference

  • https://rosettacode.org/wiki/Matrix_arithmetic#Fortran

Arguments

Type IntentOptional Attributes Name
integer, intent(in) :: n

size of a matrix

real(kind=wp), intent(in), dimension(n,n) :: a

the matrix

Return Value real(kind=wp)

the determinant of a matrix


Called by

proc~~matrix_determinant~~CalledByGraph proc~matrix_determinant matrix_module::matrix_determinant proc~matrix_determinant->proc~matrix_determinant proc~matrix_cofactor matrix_module::matrix_cofactor proc~matrix_cofactor->proc~matrix_determinant

Source Code

    pure recursive function matrix_determinant(n,a) result(det)

    implicit none

    integer,intent(in)                  :: n   !! size of `a` matrix
    real(wp),dimension(n,n),intent(in)  :: a   !! the matrix
    real(wp)                            :: det !! the determinant of `a` matrix

    integer :: i   !! counter
    integer :: sgn !! `(-1)**(i-1)` term
    real(wp), dimension(n-1, n-1) :: b  !! temp matrix

    if (n == 1) then
        det = a(1,1)
    else
        det = zero
        sgn = 1
        do i = 1, n
            b(:, :(i-1)) = a(2:, :i-1)
            b(:, i:) = a(2:, i+1:)
            det = det + sgn * a(1, i) * matrix_determinant(n-1,b)
            sgn = -sgn
        end do
    end if

    end function matrix_determinant