在Fortran 77中打印下三角形压缩矩阵

时间:2017-12-07 05:12:30

标签: matrix printing fortran fortran77 triangular

我有一个真正的* 8数字矩阵保存在数组中作为压缩的下三角矩阵:

|1  *   *   *   *   *|
|2  7   *   *   *   *| 
|3  8  12   *   *   *|
|4  9  13  16   *   *| => [1,2,3,4,5,6,7,8,9...21]
|5 10  14  17  19   *|
|6 11  15  18  20  21|

我希望能够以下列格式打印它:

 [row|col]   1  2   3   4   5   
     1       1  *   *   *   *   
     2       2  7   *   *   *   
     3       3  8  12   *   *   
     4       4  9  13  16   *   
     5       5  10 14  17  19   
     6       6  11 15  18  20  

 [row|col]   6  
     1       *  
     2       *  
     3       * 
     4       *  
     5       *   
     6       6  

我遇到的问题是我不知道如何循环到矩阵元素中而不需要创建额外的数组来按列保存元素然后打印它们。这是我到目前为止所尝试的

      Implicit Real*8 (A-H,O-Z)


      INTEGER      ARRAY(21)



      10 Format(5X,'[Row|Col]',5(8X,I6))
      Icol=6
      Num1=1
C     Test array
      DO  K=1,21
      Array(K)=K*1.0d0
      ENDO

C     Print the elements row-by-row.      
44    Num2=Icol-Num1 
      Num=Num2  
      If ((Num2).gt.5) Num=5 
      Write(*,10) (I,I=Num1,Num1+Num)
      INum1=INum1+Num
      if (Inum1.ne.Icol) goto 44       
      STOP 
      END

1 个答案:

答案 0 :(得分:1)

关键是确定指定下三角矩阵的非零元素的公式。如果i和j分别运行行和列的索引,则(j

PROGRAM print_low_tri_matrix
IMPLICIT NONE
INTEGER :: i,j,n,m,p
REAL ,ALLOCATABLE, DIMENSION(:,:) :: a
REAL, ALLOCATABLE, DIMENSION(:) :: r

n = 6
p = n*(n+1)/2   ! Number of non-zero elements in a lower triangular matrix of size n by n

ALLOCATE(a(n,n),r(p))

DO i = 1, p
        r(i) = i*1.0    ! Array containing the non-zero elements
END DO

m = 1          ! Index tracking the non-zero elements array r 
DO j = 1,n
        DO i = 1,n
                IF(j .LE. i) THEN       ! Non-zero indices of the matrix
                        a(i,j) = r(m)
                        m = m + 1
                ELSE
                        a(i,j) = 0.
                END IF
        END DO 
END DO


!       Printing the full matrix a - uncomment for checking 
!         DO i = 1,n
!                         WRITE(*,*) (a(i,j),j=1,n)
!         END DO


!       Printing the matrix a as needed
DO i = 1,n
        DO j = 1,n
                IF(j .LE. i) THEN
                        WRITE(*,'(F12.4)',ADVANCE="NO") a(i,j)
                ELSE
                        WRITE(*,'(A12)',ADVANCE="NO") '*'
                END IF

                IF (j .EQ. n ) WRITE(*,*) 
        END DO
END DO

END PROGRAM print_low_tri_matrix

输出将是:

1.0000           *           *           *           *           *
2.0000      7.0000           *           *           *           *
3.0000      8.0000     12.0000           *           *           *
4.0000      9.0000     13.0000     16.0000           *           *
5.0000     10.0000     14.0000     17.0000     19.0000           *
6.0000     11.0000     15.0000     18.0000     20.0000     21.0000

当然,如果需要,可以将矩阵更改为整数数组。

P.S: - 要在f77中使用此功能,您可以将格式说明符更改为WRITE(*,'(F12.4)',ADVANCE="NO") a(i,j)WRITE(*,'(F12.4,$)') a(i,j)。应该删除并直接定义数组的分配。