2

I want to read matrix A of dimension(n,n) from a input file, n is a variable and n<=50. For testing I took an example matrix as:

5.0   6.0   7.0
4.0   3.0    8.0
1.0   4.0    2.0

I want to read it in same format element-wise using the below code:
But when I compiled it I was getting error:

At line 15 of file partial_pivot.f90 (unit = 9, file = 'gaussj.inp') Fortran runtime error: End of file.

How this problem can be resolved?

program gaussj
implicit none
integer::i,j,n
integer,parameter::nmax=50
real,dimension(nmax,nmax)::A


 open(unit=9,file='gaussj.inp',status='old')
 n = 0
 do i = 1,nmax
   n = n+1

   read(9,*)(A(i,j),j = 1,nmax)


 end do
 close(9)

 write(25,*)((A(i,j),j=1,n),i=1,n)
end program
agentp
  • 6,849
  • 2
  • 19
  • 37
  • How big is the matrix in the file? Is it really 50x50 or is it smaller? `nmax` must correspond to the size of the matrix. – Vladimir F Героям слава Mar 22 '18 at 12:08
  • you can simply do `read(9,*)a` (no loops), then `transpose(a)` if needed – agentp Mar 22 '18 at 12:13
  • 6
    Do yourself a favour and write the dimensions of the array into the first line of the file. Then you can read the dimensions, allocate the arrays and read them. – High Performance Mark Mar 22 '18 at 12:18
  • @agentp, that's still going to try to read 2500 elements from a file providing 9. – francescalus Mar 22 '18 at 12:46
  • oh I misread, I thought he knew the dimension was 50x50 if you do not know *a priori* the number of values on a line it becomes rather cumbersome.. see for example https://stackoverflow.com/q/10661901/1004168 ( of course putting the dimension in the file makes life much simpler ) – agentp Mar 22 '18 at 13:26

1 Answers1

1

in this case if you want to assume its a square array, (and there is nothing else in the file) you can get the dimension by counting lines..

  implicit none
  integer i,n,stat
  real x
  real,allocatable::a(:,:)
  open(20,file='test.dat')
  n=-1
  stat=0
  do while(stat == 0)
     n=n+1
     read(20,*,iostat=stat)x
  enddo
  write(*,*)n
  allocate(a(n,n))
  rewind(20)
  read(20,*)a
  a=transpose(a)
  do i=1,n
     write(*,*)A(i,:)
  enddo
  end
agentp
  • 6,849
  • 2
  • 19
  • 37