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
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
Related
I am making a small code that will read numbers from 2.txt which is bunch of random real numbers, save it in a 2d array and pass it on the information to a subroutine. In the subroutine, I am assigning a particular dimension of this array to another matrix to save this for future calculation.
implicit none
double precision, allocatable :: x1(:,:)
integer :: nstep, nheatoms, k, i, j
open(unit=999,file="2.txt",status="old")
nstep = 5
nheatoms = 2
allocate(x1(3,nheatoms))
do k = 1, nstep
do i = 1, 3
do j = 1, nheatoms
read(999,*) x1(i,j)
end do
read(999,*)
end do
call diffusion(nstep,nheatoms,x1)
end do
stop
end
subroutine diffusion(nstep,nheatoms,qhecent)
implicit none
integer, intent (in) :: nheatoms, nstep
double precision :: qhecent(3,nheatoms)
integer :: j
double precision, allocatable :: qhestep(:,:)
integer :: nstepdiff, ncross
integer, save :: l = 0
double precision :: diff
l = l + 1
allocate(qhestep(nstep,nheatoms))
do j = 1, nheatoms
qhestep(l,j) = qhecent(3,j)
end do
if (l .gt. 1) then
do j = 1, nheatoms
write(*,*)qhestep(l,j), qhestep(l-1,j)
end do
end if
end subroutine
The 2.txt file is as follows:
1.0
2.1
3.2
-1.1
-2.2
-3.3
5.0
3.5
4.4
1.9
2.1
1.5
6.0
3.5
4.4
1.9
2.8
2.5
6.0
3.5
4.4
1.9
2.1
3.2
6.0
3.5
4.4
1.9
-4.3
7.9
Now if I compile with gfortran, most of the time I obtain the output as:
2.1000000000000001 -2.2000000000000002
1.5000000000000000 -3.2999999999999998
2.7999999999999998 2.1000000000000001
2.5000000000000000 1.5000000000000000
2.1000000000000001 2.7999999999999998
3.2000000000000002 2.5000000000000000
-4.2999999999999998 2.1000000000000001
7.9000000000000004 3.2000000000000002
which is expected. But if I run the code several times, an unknown number appear in the output, such as the example:
2.1000000000000001 -2.2000000000000002
1.5000000000000000 -3.2999999999999998
2.7999999999999998 1.2882297539194267E-231
2.5000000000000000 0.0000000000000000
2.1000000000000001 2.7999999999999998
3.2000000000000002 2.5000000000000000
-4.2999999999999998 2.1000000000000001
7.9000000000000004 3.2000000000000002
If I compile with ifort, then I obtain the output that have two zeros, which is wrong.
2.10000000000000 -2.20000000000000
1.50000000000000 -3.30000000000000
2.80000000000000 0.000000000000000E+000
2.50000000000000 0.000000000000000E+000
2.10000000000000 2.80000000000000
3.20000000000000 2.50000000000000
-4.30000000000000 2.10000000000000
7.90000000000000 3.20000000000000
I must stress that compiling on ifort most of the time gives correct results as in the case for gfortran. I am on a Mac OS High Sierra.
Thanks in advance.
Both compilers should give garbage results, as you are allocating qhestep in diffusion for each DO k loop. On exiting diffusion, qhestep is deallocated, so the accumulated information should be lost. That ifort returns the same heap address for qhestep on each call is misleading.
To overcome the problem, you should use allocate (qhestep(nstep,nheatoms)) before entering the DO k loop, then transfer the accumulation array in call diffusion.
That ifort gives your expected result is unfortunate, as it disguises a significant logic error. Each ALLOCATE basically provides a new memory location for the array.
You also provide no error tests when reading the file. I would recommend using iostat= for the reads and also report the data as it is read.
In summary, your approach gives the wrong result, which both compilers provide. The ifort results you provided are also wrong in some cases, but correct in others, which is misleading.
I am working on a program to calculate minimum nozzle length in supersonic nozzles (Method of Characteristics). I can't seem to figure out why my code won't write to my output file (the lines "write (6,1000)....). My code is below:
program tester
c----------------------------------------------------------------------c
implicit real (a-h,o-z)
integer count
real kminus(0:100),kplus(0:100),theta(0:100),nu(0:100),mach(0:100)
+ ,mu(0:100)
open (5,file='tester.in')
open (6,file='tester.out')
read (5,*) me
read (5,*) maxturn
read (5,*) nchar
read (5,*) theta0
close(5)
c.....set count to 0 and calculate dtheta
count=0
dtheta=(maxturn-theta0)/nchar
c.....first characteristic
do 10 an=1,nchar+1
count=count+1
c........these are already known
theta(count)=theta0+dtheta*(an-1)
nu(count)=theta(count)
c........trivial, but we will "calculate" them anyways
kminus(count)=2*theta(count)
kplus(count)=0
c........we feed it nu(count) and get m out
call pm_hall_approx(nu(count),m)
mach(count)=m
c........does not work with sqrt(...) for some reason
mu(count)=atan((1/(mach(count)**2)-1)**0.5)
write (6,1000) count,kminus(count),kplus(count),theta(count)
+ ,nu(count),mach(count),mu(count)
10 continue
c.....the other characteristics
do 30 bn=1,nchar
do 20 cn=1,(nchar+1-bn)
count=count+1
c...........these are given
kminus(count)=kminus(cn+bn)
kplus(count)=-1*kplus(bn+1)
c...........if this is the last point, copy the previous values
if (cn.eq.(nchar+1-bn)) then
kminus(count)=kminus(count-1)
kplus(count)=kplus(count-1)
endif
c...........calculate theta and nu
theta(count)=0.5*(kminus(count)+kplus(count))
nu(count)=0.5*(kminus(count)-kplus(count))
c...........calculate m
call pm_hall_approx(nu(count),m)
mach(count)=m
mu(count)=atan((1/(mach(count)**2)-1)**0.5)
write (6,1000) count,kminus(count),kplus(count),theta(count)
+ ,nu(count),mach(count),mu(count)
20 continue
30 continue
close(6)
stop
1000 format (11(1pe12.4))
end
c======================================================================c
include 'pm_hall_approx.f'
And my subroutine is given here:
subroutine pm_hall_approx(nu,mach)
c----------------------------------------------------------------------c
c Given a Mach number, use the Hall Approximation to calculate the
c Prandtl-Meyer Function.
c----------------------------------------------------------------------c
implicit real (a-h,o-z)
c.....set constants
parameter (a=1.3604,b=0.0962,c=-0.5127,d=-0.6722,e=-0.3278)
parameter (numax=2.2769)
y=nu/numax
mach=(1+a*y+b*y*y+c*y*y*y)/(1+d*y+e*y*y)
return
end
And here are the contents of tester.in
2.4 = mache
5.0 = maxturn
7 = nchar
0.375 = theta0
In fortran, unit number 6 is reserved for screen. Never use that as the unit number. Try changing it to some other number like write(7,1000) and then it should work.
I am having trouble reading exponential from a text file using Fortran.
The entry in the text file looks like the following
0.02547163e+06-0.04601176e+01 0.02500000e+02 0.00000000e+00 0.00000000e+00 3
And the code that I am using looks like the following
read(iunit,'(ES20.8,ES20.8,ES20.8,ES20.8,ES20.8,I2)') dummy1, dummy2, Thermo_DB_Coeffs_LowT(iS,1:3),temp
The error I am getting is
Fortran runtime error: Bad value during floating point read
How can I read these values?
Well here is what I usually do when it is too painful to hand edit the file...
CHARACTER(LEN=256) :: Line
INTEGER, PARAMETER :: Start = 1
INTEGER :: Fin, Trailing_Int, I
DOUBLE, DIMENSION(6) :: Element
...
Ingest_All_Rows: DO WHILE(.TRUE.)
READ(...) Line ! Into a character-string
<if we get to the end of the file, then 'EXIT Ingest_All_Rows'>
Start =1
Single_Row_Ingest: DO I = 1, 6
Fin = SCAN(Line,'eE')+3 !or maybe it is 4?
IF(I ==6) Fin = LEN_TRIM(Line)
READ(Line(Start:Fin),*) Element(I) !fron the string(len-string) to the double.
Line = Line((Fin+1):)
IF(I ==6) Trailing_Int = Element(6)
ENDDO Single_Row_Ingest
<Here we shove the row's 5 elements into some array, and the trailing int somewhere>
ENDDO Ingest_All_Rows
You will have to fill in the blanks, but I find that SCAN and LEN_TRIM can be useful in these cases
I'm completely new in Fortran and I need to write some relatively simple codes.
I have some files (various, for example 200 files); each file for the specific node, with some simplification, each file contains:
T(i), X(i)
these are my input and I want to have an output file contain:
T(i) X(i)1 X(i)2 ... X(i)n
the problem is that I can't separate data in different columns of output file, they comes all after each other in 1 column.
My code is :
PROGRAM Output
implicit none
integer ::nn,n,i,j,l
real,dimension(:),allocatable::t,x,y,z
character(len=10)::TD
open(11,file='outputX.txt')
allocate (t(1000),x(1000),y(1000),z(1000))
n=5 ! Number of Files
nn=50 ! Number of Rows in each File
Do i=1,n ! loop for opening different files
write(TD,10)i
write(*,*)TD
open(1,file=TD)
Do l=1,nn ! loop for reading rows in each file
read(1,*)t(j),x(j)
write(11,*)x(j) !!!! This is my PROBLEM, all the data shows in
! one column, I want each file in separately
Enddo
Enddo
10 format('100',i3.3,'')
deallocate(x,y,z,t)
END PROGRAM Output
The output I get is like this :
11
12
13
21
22
23
31
32
33
But in fact I want :
11 21 31
12 22 32
13 23 33
There are several problems with your code
Do i=1,n ! loop for opening different files
write(TD,10)i
write(*,*)TD
open(1,file=TD)
Do l=1,nn ! loop for reading rows in each file
read(1,*)t(j),x(j)
write(11,*)x(j) !!!! This is my PROBLEM, all the data shows in
! one column, I want each file in separately
End do
End do
The index j is completely undefined. You should put j=1 or 0 and j=j+1 somewhere inside the loop.
The other issue is your output. You are reading the files in sequence. It is very hard to print each file into a separate column. A separate row for each file is easy:
write(11,*) x(1:nn)
after the inner loop.
Or with finer control and avoiding a line wrap
write(11,'999(g0,1x)') x(1:nn)
(g0 is a general edit descriptor which uses only the necessary width). This will only work if you fix the j issue I mentioned above!
To put it into separate columns you must
Open all files at the same time, then read from each of them and print the read data in a single write command.
or
Store all the data from all files into separate columns in a 2D array and print the 2D array afterwards.
So what I got is x(1) belongs to 11, x(2) belongs to 12, x(3) belongs to 13 and so on, isn't it? You could try this one:
write(11,100) x(j), x(j+3), x(j+6)
100 format(1X,11F20.4,11F20.4,11F20.4)
The 2D array... for this problem it is backwards
But it should give you some help... (Hopefully)
PROGRAM Output
IMPLICIT NONE
INTEGER, PARAMETER :: nfiles = 5
INTEGER, PARAMETER :: nrows = 50
integer :: iFile, iRow !File and row counter/#
real,dimension(:,:),allocatable :: t,x,y,z !The are now 2D
INTEGER,dimension(nFiles) :: lFile !logical file indexed by file#
LOGICAL,dimension(nFiles) :: Open4Biz !logical for closing
character(len=10)::TD !Unsure about this
open(11,file='outputX.txt')
allocate (t(iRow,iFile),x(iRow,iFile),y(iRow,iFile),z(iRow,iFile))
Open4Biz(:) = .FALSE. !Initialize
!n=5 ! Number of Files ^^Moved up/renamed^^
!nn=50 ! Number of Rows in each File ^^Moved up/renamed^^
Files_Loop1: Do iFile = 1, nFiles !I think that the loop identifier is std f95 (std ifort anyhow)
write(TD,10) iFile !Unsure about this
write(*,*)TD
lFile(iFile) = 10+iFile
open(lFile(iFile),file=TD) !Probably put in some logic if the file is not found
Open4Biz(iFile) = .TRUE.
ENDDO Files_Loop1
Rows_Loop: Do iRow = 1, nn !The loops are backwards from normal
Files_Loop2: Do iFile = 1, nFiles
read(lFile(iFile),*) t(iRow, iFile), x(iRow, iFile)
Enddo Files_Loop2
write(11,*) x(iRow,:)
Enddo Rows_Loop
10 format('100',i3.3,'')
667 CONTINUE !This is label to 'jump to' from a bad open
Files_Loop3: Do iFile = 1, nFiles
IF(Open4Biz(iFile) CLOSE(lFile(iFile))
ENDDO Files_Open_Loop
IF(ALLOCATED(X)) deallocate(x)
IF(ALLOCATED(Y)) deallocate(y)
IF(ALLOCATED(Z)) deallocate(z)
IF(ALLOCATED(T)) deallocate(t)
END PROGRAM Output
I am currently writing a code to simulate particle collisions. I am trying to open as much files as there are particles (N) and then put the data for positions and velocities in each of these files for each step of the time integration (using Euler's method, but that is not relevant). For that, I tried using a do loop so it will open all the files I need - then I put all the data in them with a different do loop later - and then close them all.
I first tried just doing a do loop to open the files - but it gave errors of the type "file already open in another unit", so I did the following:
module parameters
implicit none
character :: posvel
integer :: i, j, N
real :: tmax
real, parameter :: tmin=0.0, pi=3.14159265, k=500.0*10E3, dt=10.0E-5, dx=10.0E-3, g=9.806, ro=1.5*10E3
real, dimension(:), allocatable :: xold, xnew, vold, vnew, m, F, r
end module parameters
PROGRAM Collision
use parameters
implicit none
write(*,*) 'Enter total number of particles (integer number):'
read(*,*) N
allocate(xold(N))
allocate(vold(N))
allocate(xnew(N))
allocate(vnew(N))
allocate(m(N))
allocate(F(N))
allocate(r(N))
xold(1) = 0.0
vold(1) = 0.0
m(1) = 6.283*10E-9
r(1) = 10E-4
xold(2) = 5.0
vold(2) = 0.0
m(2) = 6.283*10E-9
r(2) = 10E-4
write(*,*) 'Type total time elapsed for the simulation(real number):'
read(*,*) tmax
do i = 1, N
write(posvel,"(a,i3.3,a)") "posveldata",i,".txt"
open(unit=i,file=posvel, status="unknown")
end do
do i = 1, N
close(unit=i)
end do
END PROGRAM Collision
The last ten lines are the ones that regard to my problem.
That worked in codeblocks - it opened just the number of files I needed, but I'm actually using gfortran and it gives me and "end of record" error in the write statement.
How can I make it to execute properly and give me the N different files that I need?
P.S.: It is not a problem of compilation, but after I execute the program.
Your character string in the parameter module has only 1 character length, so it cannot contain the full file name. So please use a longer string, for example
character(100) :: posvel
Then you can open each file as
do i = 1, N
write(posvel,"(a,i0,a)") "posveldata",i,".txt"
open(unit=i,file=trim(posvel), status="unknown")
end do
Here, I have used the format i0 to automatically determine a proper width for integer, and trim() for removing unnecessary blanks in the file name (though they may not be necessary). The write statement can also be written more compactly as
write(posvel,"('posveldata',i0,'.txt')") i
by embedding character literals into the format specification.
The error message "End of record" comes from the above issue. This can be confirmed by the following code
character c
write(c,"(a)") "1"
print *, "c = ", c
write(c,"(a)") "23" !! line 8 in test.f90
print *, "c = ", c
for which gfortran gives
c = 1
At line 8 of file test.f90
Fortran runtime error: End of record
This means that while c is used as an internal file, this "file" does not have enough space to accommodate two characters (here "23"). For comparison, ifort14 gives
c = 1
forrtl: severe (66): output statement overflows record, unit -5, file Internal Formatted Write
while Oracle Fortran12 gives
c = 1
****** FORTRAN RUN-TIME SYSTEM ******
Error 1010: record too long
Location: the WRITE statement at line 8 of "test.f90"
Aborted
(It is interesting that Oracle Fortran reports the record to be "too long", which may refer to the input string.)