The problem is, that at every iteration in your do loop you try to read in as many elements as you have in the entire array mat
. You should fill only one column in each iteration. Alternatively, you can read in the entire array with one read statement without any loops.
As for the writing, you need to repeat the format as many times as you have columns. I'd suggest to create a format string dynamically, so that it is automatically adapted to the number of columns entered by the user. See the example below. You can omit the do loop for the writing as well, as Fortran will automatically add an end of record sign (a newline), when all format specification had been consumed, and it will start to apply them again.
program refgrid
implicit none
integer :: nrow, ncol
real, allocatable :: mat(:,:)
character(20) :: form
print *, ' Input number of rows: '
read *, nrow
print *, 'Input number of columns: '
read *, ncol
allocate(mat(1:ncol, 1:nrow))
open(unit=1, file='bathymetry2.dat', status='OLD', action='READ')
read(1, *) mat
close(1)
write(form, "(A,I0,A)") "(", ncol, "F10.4)"
open(1, file='refgrid.dat', form='FORMATTED', status='NEW', action='WRITE')
write(1, form) mat
close(1)
end program refgrid
UPDATE: As for the dynamic creation of the format specifier: You write into the string form
three things: a string (A
), an integer with only as many characters as it requires (I0
) and an other string (A
). The first string is (
, the integer is ncol
and the second string is F10.4)
. So, provided ncol
had the value 128
, you will have in form
the string (128F10.4)
. This is a string containing a valid format specifier, so you can use it in your write statement instead of a hard coded format specifier.