Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Section Arrays: Trace

---
jupytext:
  formats: md:myst
  text_representation:
    extension: .md
    format_name: myst
kernelspec:
  display_name: Python 3
  language: python
  name: python3
---

Section Arrays: Trace

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.9330 0.4876 0.0668 0.9786 0.2594
 0.1871 0.7684 0.8930 0.6321 0.4436
 0.5485 0.3307 0.1294 0.7826 0.9822
 0.0884 0.9759 0.9920 0.7120 0.5354
 0.1844 0.1664 0.0254 0.4800 0.5832

trace =  3.1261