I wanted to write a subroutine in modern fortran (90 or newer) to write the elements of a given matrix into a file output.txt. Each line of the file output.txt contains the elements of each row of the matrix (the natural).
The following is an example (of course, it is not a subrutine depending on a matrix A, is a function fix the matrix defined inside just to explain you my questions).
PROGRAM testing
!
IMPLICIT NONE
!
REAL, ALLOCATABLE :: A(:,:)
INTEGER :: i, j, n, m
CHARACTER(LEN=20) :: opt
!
m = 3
n = 4
!
ALLOCATE( A(n,m))
A(1,:) = (/ 1 , 2 , 3 , 4 /)
A(2,:) = (/ -1 , -2 , -3 , -4 /)
A(3,:) = (/ 10 , 20 , 30 , 40 /)
!
!
opt = '(4(e25.15,1x))' ! <--- I NEED THE VALUE OF M INSTEAD OF 3 HERE !!!!!!
OPEN(1, file='output.txt', status='replace', action='write')
DO i = 1,m
WRITE(1,opt) ( A(i,j) , j=1,n )
END DO
CLOSE(1)
!
END PROGRAM testing
My problem is that "4" in the opt variable. I wanted to have define
opt = '(4(e25.15,1x))'
but depending on n (the number of columns of the matrix):
opt = '(n(e25.15,1x))'
Y tried to do a cast, something like:
character :: aux(44)
integer :: i
i = 3
write (aux, "(A5,I40)") '(', i
opt = '('//TRIM(aux)//'(e25.15,1x))'
but this depends on the 40. If the number of columns is too big this going to fail.
Do you know how to do this? Maybe there are a better option to write the matrix into an output file.