Beliavsky / FortranTip

Short instructional Fortran codes associated with Twitter @FortranTip
https://zmoon.github.io/FortranTipBrowser/
The Unlicense
64 stars 14 forks source link

Tip: growing array with move_alloc #45

Closed aslozada closed 2 years ago

aslozada commented 2 years ago

this tip can be useful for simulating systems that change size on the fly, for example

program main
  implicit none
  integer, allocatable :: matrix(:,:)
  integer, allocatable :: temporary(:,:)
  integer :: old_rows, old_cols, new_cols
  integer :: i, j, n

  old_rows=3
  old_cols=3
  n=3

 allocate(matrix(old_rows,old_cols),source=0)

  do j = 1, old_rows
     write(*,*) matrix(j,:)
  end do

  do i = 1, n
      new_cols=old_cols+1

      allocate(temporary(old_rows,new_cols),source=1)
      temporary(1:old_rows,1:old_cols) = matrix(1:old_rows,1:old_cols)

      call move_alloc(from=temporary,to=matrix)

      write(*,*)
      do j = 1, old_rows
         write(*,*) matrix(j,:)
      end do

      old_cols=new_cols
    end do

 end program main

output


000
000
000

0001
0001
0001

00011
00011
00011