Section Arrays: Trace#

Adapted from: gjbex/Fortran-MOOC

This program demonstrates computing the trace of a matrix in Fortran.#

program compute_trace
    implicit none
    integer :: i
    real, dimension(5, 5) :: A

    call random_number(A)
    do i = 1, size(A, 1)
        print '(5F7.4)', A(i, :)
    end do
    print '(/, A, F7.4)', 'trace = ', trace(A)

contains

    real function trace(matrix)
        use, intrinsic :: iso_fortran_env, only : error_unit
        implicit none
        real, dimension(:, :), intent(in) :: matrix
        integer :: i

        if (size(matrix, 1) /= size(matrix, 2)) then
            write (unit=error_unit, fmt='(A)') &
                'error: can not compute trace of a non-square matrix'
            stop 1
        end if
        trace = 0.0
        do i = 1, size(matrix, 1)
            trace = trace + matrix(i, i)
        end do
    end function trace

end program compute_trace

The above program is compiled and run using Fortran Package Manager (fpm):

Build the Program using FPM (Fortran Package Manager)#

import os
root_dir = os.getcwd()
code_dir = root_dir + "/" + "Fortran_Code/Section_Arrays_Trace"
os.chdir(code_dir)
build_status = os.system("fpm build 2>/dev/null")

Run the Program using FPM (Fortran Package Manager)#

exec_status = os.system("fpm run 2>/dev/null")
 0.9610 0.6726 0.4475 0.8218 0.3841
 0.8341 0.0311 0.2360 0.1143 0.6879
 0.0055 0.5002 0.5859 0.7982 0.3812
 0.5301 0.1466 0.2009 0.7046 0.3459
 0.0723 0.2089 0.8568 0.8248 0.5118

trace =  2.7944