-
Notifications
You must be signed in to change notification settings - Fork 1
/
TriangleMatrix.f95
66 lines (62 loc) · 2.11 KB
/
TriangleMatrix.f95
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
! 使用行变换,将矩阵转换为上三角矩阵与下三角矩阵。
! 此程序中含有不足之处,即无法自动进行交换行操作,所以数据中可能会出现NaN的情况。
MODULE LINEAR_ALGEBRA
IMPLICIT NONE
PUBLIC N
PUBLIC SHOWMAT
PUBLIC UPPER
PUBLIC LOWER
INTEGER, PARAMETER :: N = 3
CONTAINS
! 显示矩阵内容
SUBROUTINE SHOWMAT(MATRIX)
IMPLICIT NONE
REAL, INTENT(IN) :: MATRIX(:, :)
INTEGER :: I
DO I=1, SIZE(MATRIX, 2) ! 遍历矩阵的行
WRITE(*, "(4F8.2)") MATRIX(:, I)
END DO
RETURN
END SUBROUTINE
! 求上三角矩阵的子程序
SUBROUTINE UPPER(MATRIX)
IMPLICIT NONE
REAL, INTENT(INOUT) :: MATRIX(:, :)
INTEGER :: I, J
! 进行矩阵的行变换
DO I=1, SIZE(MATRIX, 2)-1
DO J=I+1, SIZE(MATRIX, 2)
MATRIX(:, J) = MATRIX(:, J) - MATRIX(I, J) * MATRIX(:, I) / MATRIX(I, I)
END DO
END DO
RETURN
END SUBROUTINE
! 求下三角矩阵的子程序
SUBROUTINE LOWER(MATRIX)
IMPLICIT NONE
REAL, INTENT(INOUT) :: MATRIX(:, :)
INTEGER :: I
INTEGER :: J
! 进行矩阵的行变换
DO I=SIZE(MATRIX, 2), 2, -1
DO J=I-1, 1, -1
MATRIX(:, J) = MATRIX(:, J) - MATRIX(I, J) &
* (MATRIX(:, I) / MATRIX(I, I))
END DO
END DO
END SUBROUTINE
END MODULE
PROGRAM MAIN
USE LINEAR_ALGEBRA
IMPLICIT NONE
REAL :: A(N, N) = (/ 1, 2, 1, 3, 2, 3, 2, 3, 4 /)
REAL :: B(N, N)
B = A
CALL SHOWMAT(A)
CALL UPPER(A)
WRITE(*, *) "------------------"
CALL SHOWMAT(A)
WRITE(*, *) "------------------"
CALL LOWER(B)
CALL SHOWMAT(B)
END PROGRAM