如何确定文本文件中几个矩阵的维

时间:2018-10-10 13:49:07

标签: multidimensional-array fortran fortran90 dynamic-arrays

我想知道几个矩阵的尺寸,这些尺寸是我从文件中读取的。 我已经完成了计算矩阵的行数和元素总数的代码,因此知道了列数,将元素总数除以行数。

program matrix
    implicit none

    integer,dimension(:),allocatable::total
    integer row,io,countRows,columns,m,numElements

    open(12,file='matrix.txt',status='old',iostat=io)
    if (io.ne.0) then
        write(*,*)'error to open file'
        stop
    end if

    !count rows
    countRows=0
    io=0
    do while (io.ge.0)
        read(12,*,iostat=io) row
        if (io.eq.0) countRows=countRows+1
    end do
    rewind(12)

    !total of elements
    io=0
    do m=1,1000
        allocate(total(m))
        read(12,*,iostat=io) total
        deallocate(total)
        rewind(12)
        if (io.ne.0) exit
    end do

    numElements=size(total)-1
    columns=numElements/countRows

    close(12)
end program

问题在于,它仅在文件中存在矩阵时才起作用,因为如果有多个矩阵(由一个或几个空行分隔),它将告诉我文件的总行数和总元素数。 我需要知道如何分离这些矩阵以独立地计算其行和列。

示例文件可能看起来像

90 21 11 13
12 11 10 11
33 44 76 55

12 12
87 99

33 12 17
45 98 77

1 个答案:

答案 0 :(得分:1)

我可以提出这样的解决方案,而不是花哨的解决方案,但似乎可以与示例配合使用:

program matrix
    implicit none

    integer,dimension(:),allocatable::total
    integer row,io,countRows,columns,m,numElements,icol
    integer mlocs(100,2),imat,countMat,countSpace,nmats
    character(len=256) line
    character linechar

    mlocs=0;
    open(12,file='matrix.txt',status='old',iostat=io)
    if (io.ne.0) then
        write(*,*)'error to open file'
        stop
    end if

    !count rows
    countRows=0
    countMat=1;countSpace=0;

    do while (1.gt.0.0)
        read(12,'(a)',end=100) line
        print*,trim(line)
        countRows=countRows+1;countSpace=1;
        if (len(trim(line)).eq.0) then
            countMat=countMat+1;mlocs(countMat,1)=countRows;
        elseif (len(trim(line)).gt.0) then
            do icol=1,len(trim(line))
                read(line(icol:icol),'(a)') linechar
                if (linechar.eq.' ') then 
                  countSpace=countSpace+1;
                  mlocs(countMat,2)=countSpace
                endif
            enddo
        endif
    end do
100 print*,'Number of lines is ',countRows
    print*,'Number of matrices is ',countMat
    nmats=countMat;

    do imat=1,nmats
       print*,'NUmber of elements in matrix ',imat,' is ',mlocs(imat,2:2)
    enddo

    close(12)
end program