0

我有一个实数* 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
4

1 回答 1

1

关键是要确定指定下三角矩阵非零元素的公式。如果 i 和 j 分别是行和列的运行索引,则 (j < i) 元素将位于下三角形部分。这是代码:

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

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

PS :- 要在 f77 中进行这项工作,您可以将格式说明符更改 WRITE(*,'(F12.4)',ADVANCE="NO") a(i,j)WRITE(*,'(F12.4,$)') a(i,j). 应该直接删除和定义数组的分配。

于 2017-12-07T12:41:18.630 回答