Printing a Fortran Array with write
February 6, 2006
Fortran write
statement. This can be a problem if you want to print a number of elements on
the same line, but you don’t know how many elements there will be at compile
time. Specifically, if you want to print a matrix or two-dimensional array
but you don’t know the dimensions, you probably want to do something like the
following:
do, i=1:m
do, j=1:n
write (*,*) matrix(i,j)
enddo
enddo
Unfortunately, this will simply print all m*n numbers on separate lines
because each write is followed by a newline.
There seems to be no real standard advance="no" to the end of the format descriptor:
write(*,"(A)",advance="no") "One "
write(*,"(A)") "line."
Other earlier compilers support adding either \ or $ to the end of the
format descriptor:
write(*,'(A,$)') 'One '
write(*,'(A)') 'line.'
Neither of these approaches worked with GNU g77. Instead, I used an implied do loop:
do, i=1,m
write(*,"100g15.5") ( matrix(i,j), j=1,n )
enddo
The outer loop runs over each row of the matrix and the inner implied do loop lists each entry in row i.
References
WRITE without newline?,
comp.lang.fortran, 26 May 1998.Page, Clive. Professional Programmer’s Guide to Fortran77, 2005.