Looping over defined array elements in Fortran

1.2k views Asked by At

Hello I am currently trying to find out the best way of identifying how many items have been added to an array in Fortran. To better explain the question I have simplified the system I am working with to act as an example.

Let’s say I have a box with 11 atoms bouncing around in it. At each timeframe I identify all atoms that are within a certain distance of my favourite atom, atom_α, and add them to an array named array_C, (of length 10). Now I would then like to iterate over array_C and perform calculations on the atoms in it. In python this would be no big deal as the list is long as the number of elements in it. In fortran the list/array is defined by you, and is as long as you say it is (in this case 10). As the other atoms could be far or close to atom_α the array, array_C, could contain 0, 10 or any number of atoms between. So if I was to loop over array_C I may loop over an “empty” cell or a cell that had not been overwritten from the last step causing all sorts of problems. How would I deal with this issue or is it simply a case of keeping track of the number of atoms I added to the array and then doing a do loop over it using that value?

In reality there are around 4000 atoms and each atom is a “Class” like object each containing, amongst other things, their own “array_C” listing which other atoms are close to it.

Thank you for your time.

1

There are 1 answers

0
Ross On

You should declare an array to have length greater than what you expect to need. When adding elements to that array, keep track of the number of elements you have added (called numElements in the example). Then you can loop from 1 to numElements - elements of the array greater than that number are not used in that timestep. For example:

integer, parameter :: maxElements = 10000
integer :: i, numElements
real :: curData, myData(maxElements)

numElements = 0

! Adding elements to list
do         ! Over all atoms
   if      ! Atom is close
      ! Include atom in list myData
      ! and increment numElements

      numElements = numElements + 1

      if (numElements > maxElements) then
         ! Error
      endif

      myData(numElements) = ...
   endif
enddo

! Now loop over list
do i=1,numElements
   curData = myData(i)

   ! Calculations with curData
enddo

Does that make sense? I agree with vlad that the question is difficult to understand so please give us more specifics if you need more answers.