Write a matrix to a file.
sergio santos
02-11-2008, 07:33 PM
How would you write a 2D array to a file - basically write a matrix to a file line by line?
davekw7x
02-13-2008, 10:21 AM
How would you write a 2D array to a file - basically write a matrix to a file line by line?
PROGRAM test
! Show matrix creation and writing
USE nrtype
! Probably will also USE nr in your application
IMPLICIT NONE
INTEGER(I4B), PARAMETER :: MP=20,NP=20
REAL(SP), DIMENSION(NP,NP) :: u
INTEGER(I4B) :: i,j,n
! n can have any value such that 1 <= n <= NP
n = 3
do i=1,n
do j=1,n
u(i,j) = (i-1)*n+j
end do
end do
! Standard output
do i=1,n
write(*,'(1x,(1p6e14.6))') (u(i,j), j=1,n)
end do
! File output
open(8,file='result.dat', status='new')
do i=1,n
write(8,'(1x,(1p6e14.6))') (u(i,j), j=1,n)
end do
close(8)
END PROGRAM test
Output to console and to file "result.dat":
1.000000E+00 2.000000E+00 3.000000E+00
4.000000E+00 5.000000E+00 6.000000E+00
7.000000E+00 8.000000E+00 9.000000E+00
Regards,
Dave