1

I'm new to Fortran so I'm really lost on how to do this. I have a data file with 5 groups of 5000 values. My code reads in the first 5000 values and puts them in an array called flux, does some stuff, then cycles back through to read the next set of 5000 values (while deleting the values in the original flux array and storing the new ones).

I need to be able to save each value so that I can plot them all later. I was hoping to to take the flux array values and append them to a different array, that way at the end of the loop I have one array with all 25,000 values in it. In Python this would be a one liner, but from what I'm reading online it seems this is not easy to do in Fortran.

Thanks in advance!

real, allocatable :: flux(:), s(:)      
      open(1,file='spec_1503-070_th45',status='old')
      read(1,*) nf
      read(1,*) (xlam(ij),ij = 1,nf)
      read(1,'(25x,f10.1,12x,e10.3)')teff,grav
      write(header,111) int(teff),alog10(grav)

      do il=100,1000
         read(1,*,end=99) bmag,az,ax,ay
         read(1,*)(flux(ij),ij = 1,nf)
         fmax=0.
         do ij=1,nf
            if(flux(ij).gt.fmax) fmax=flux(ij)
         enddo
         do ij=1,nf
            flux(ij)=flux(ij)/fmax
         enddo
         s=[s,flux]
Hawkmoon
  • 23
  • 3

1 Answers1

1

Appending to or resizing arrays in Fortran is as simple as declaring them as an allocatable array,

integer, allocatable :: vecA(:), vecB(:), vecC(:)
character(*), parameter :: csv = "(*(g0,:,', '))"
vecA = [1,2,3]
vecB = [4,5,6]
vecC = [vecA, vecB]
write(*,csv) "vecA", vecA
write(*,csv) "vecB", vecB
write(*,csv) "vecC", vecC
vecC = [vecC, vecC(size(vecC):1:-1)]
write(*,csv) "vecC", vecC
end
vecA, 1, 2, 3
vecB, 4, 5, 6
vecC, 1, 2, 3, 4, 5, 6
vecC, 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1

The left-hand side is automatically resized to the proper length. Notice, how vecC = [vecC,vecC] doubles the length of vecC. If you have performance-critical code, you probably would want to avoid such automatic reallocations. But that becomes relevant only when the code is to be called on the order of billions of times.

Scientist
  • 1,767
  • 2
  • 12
  • 20
  • Unfortunately I had tried this already and it does not work the way I've done it, leads to a memory allocation error. I posted my code in the original question, maybe I'm not implementing it correctly but I'm not sure. – Hawkmoon Jan 19 '22 at 17:02