Not the fastest way, but working for small matrices in GFortran. This solution is given for rectangular integer matrices, but I guess it can be easily transformed for real matrices as it was in the question. I'm a newbie in coding, so any improvements would be welcome.
Program Example
Implicit none
Integer, allocatable, dimension(:,:) :: A
Integer :: M, N ! numbers of rows and columns of the input matrix
Integer :: i
Character(len=20) :: FMT ! variable format for rows of the matrix
Open(1, FILE='In.txt') ! file with the input matrix
Open(2, FILE='Out.txt') ! file for its copy
Call ReadArray(A, M, N)
Write(FMT,"( '(',I0,'(I4))') ") N
Write(2,*) 'Input matrix:'
Write(2,FMT)(A(i,:),i=1,M)
Deallocate(A)
CONTAINS
Subroutine ReadArray(Array, M, N)
Integer, intent(out), Allocatable, Dimension(:,:) :: Array
Integer, intent(out) :: M, N ! matrix dimensions
Integer, Allocatable, Dimension(:,:) :: T ! temporary matrix
Integer, Allocatable, dimension(:) :: RV ! current row vector
Character*100 s ! processed line from the input file
Character :: d = ' ' ! delimiter
Integer stat, p, q, r
M = 0 ! number of rows
N = 0 ! number of columns
stat=0
Do while(.TRUE.)
Read (1, '(a)', iostat=stat) s
if (stat /= 0) exit
M = M + 1
If (N==0) then ! determine number of columns
p = 1
Do
q = verify( s(p:), d) ! position of a first non-delimiting symbol
if (q == 0) exit
r = scan( s(p+q:), d) ! length of the current number
N = N + 1
p = p + (q-1) + (r-1) + 1
End Do
Allocate( RV(1:N) )
End if
Read(s,*) RV(1:N)
If (M==1) then
Allocate (Array(M,N))
Else
Deallocate( Array )
Allocate( Array(M,N) )
Array(:M-1,:) = T
Deallocate( T )
End if
Array(M,:) = RV
Allocate( T(M,N) )
T(:,:) = Array
End Do
Deallocate( RV, T )
End Subroutine ReadArray
End Program Example
nmaxmust correspond to the size of the matrix.read(9,*)a(no loops), thentranspose(a)if needed