Section Arrays: Normalize#
Adapted from: gjbex/Fortran-MOOC
This program normalizes a randomly generated matrix in Fortran.#
program normalize
use, intrinsic :: iso_fortran_env, only : error_unit, DP => REAL64
implicit none
integer, parameter :: rows = 3, cols = 4
real(kind=DP), dimension(rows, cols) :: matrix, spread_norm
real(kind=DP), dimension(rows) :: norm
call random_number(matrix)
print '(A)', 'original:'
call print_matrix(matrix)
norm = sum(matrix, dim=2)
print '(A, *(F12.7))', 'norm:', norm
spread_norm = spread(norm, 2, size(matrix, 2))
call print_matrix(spread_norm)
matrix = matrix/spread_norm
print '(A)', 'row-normalized::'
call print_matrix(matrix)
norm = sum(matrix, dim=2)
print '(A, *(F12.7))', 'norm:', norm
contains
subroutine print_matrix(matrix)
implicit none
real(kind=DP), dimension(:, :), intent(in) :: matrix
integer :: row
do row = 1, size(matrix, 1)
print '(*(F12.7))', matrix(row, :)
end do
end subroutine print_matrix
end program normalize
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_Normalize"
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")
original:
0.7536383 0.2732597 0.3627242 0.7129912
0.7138595 0.2689572 0.9106335 0.1092950
0.2025349 0.6838653 0.6392817 0.7773715
norm: 2.1026134 2.0027453 2.3030533
2.1026134 2.1026134 2.1026134 2.1026134
2.0027453 2.0027453 2.0027453 2.0027453
2.3030533 2.3030533 2.3030533 2.3030533
row-normalized::
0.3584293 0.1299619 0.1725111 0.3390976
0.3564405 0.1342943 0.4546926 0.0545726
0.0879419 0.2969385 0.2775801 0.3375395
norm: 1.0000000 1.0000000 1.0000000
exec_status = os.system("fpm run 2>/dev/null")
original:
0.7696286 0.9930188 0.3282832 0.9808132
0.9729438 0.8957851 0.1640371 0.4562588
0.2086180 0.0232612 0.1982778 0.3526204
norm: 3.0717438 2.4890248 0.7827774
3.0717438 3.0717438 3.0717438 3.0717438
2.4890248 2.4890248 2.4890248 2.4890248
0.7827774 0.7827774 0.7827774 0.7827774
row-normalized::
0.2505510 0.3232753 0.1068719 0.3193018
0.3908936 0.3598940 0.0659042 0.1833083
0.2665101 0.0297162 0.2533004 0.4504734
norm: 1.0000000 1.0000000 1.0000000
exec_status = os.system("fpm run 2>/dev/null")
original:
0.5949331 0.9534930 0.7966856 0.2406519
0.8167731 0.5869952 0.4933111 0.5366718
0.2677453 0.4013981 0.7208525 0.9709283
norm: 2.5857636 2.4337513 2.3609242
2.5857636 2.5857636 2.5857636 2.5857636
2.4337513 2.4337513 2.4337513 2.4337513
2.3609242 2.3609242 2.3609242 2.3609242
row-normalized::
0.2300802 0.3687472 0.3081046 0.0930680
0.3356025 0.2411895 0.2026958 0.2205122
0.1134070 0.1700174 0.3053264 0.4112492
norm: 1.0000000 1.0000000 1.0000000