Read data and append it to array, best practice?

You can write a function to combine matrices by row, as shown in the program:

module m
implicit none
contains
function rbind(a,b) result(ab)
! combine matrices a and b by row
integer, intent(in)  :: a(:,:),b(:,:)
integer, allocatable :: ab(:,:)
integer              :: n1a,n1,n2
n2 = size(a,2)
if (size(b,2) /= n2) stop "need size(a,2) == size(b,2)"
n1a = size(a,1)
n1 = n1a + size(b,1)
allocate (ab(n1,n2))
ab(:n1a,:)   = a
ab(n1a+1:,:) = b
end function rbind
end module m

program main
use m, only: rbind
implicit none
integer, allocatable :: i1(:,:),i2(:,:)
integer, parameter   :: n1_1 = 2, n1_2 = 3, n2 = 2
i1 = reshape([10,11,20,21],[n1_1,n2])
write (*,*) "i1"
write (*,"(2i5)") transpose(i1)
i2 = reshape([12,13,14,22,23,24],[n1_2,n2])
i1 = rbind(i1,i2)
write (*,*) "i2"
write (*,"(2i5)") transpose(i2)
write (*,*) "combined"
write (*,"(2i5)") transpose(i1)
end program main

The function rbind is named after the one in R. The program gives output

 i1
   10   20
   11   21
 i2
   12   22
   13   23
   14   24
 combined
   10   20
   11   21
   12   22
   13   23
   14   24
2 Likes