# Read data and append it to array, best practice?

**URL:** <https://fortran-lang.discourse.group/t/read-data-and-append-it-to-array-best-practice/1915>\
**Category:** Help\
**Created:** [September 22, 2021, 2:39pm UTC](https://fortran-lang.discourse.group/t/read-data-and-append-it-to-array-best-practice/1915 "2021-09-22T14:39:15Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![Beliavsky](https://avatars.discourse-cdn.com/v4/letter/b/ba8739/32.png) [@Beliavsky](https://fortran-lang.discourse.group/u/Beliavsky)\
**Post date:** [September 22, 2021, 4:54pm UTC](https://fortran-lang.discourse.group/t/read-data-and-append-it-to-array-best-practice/1915/6 "2021-09-22T16:54:50Z")

</div>

> [@hohoho](#):
>
> Thank you for your answers, I did not know this existed. I used what you guys showed me succesfully for 1D data.
> 
> - Is it really _allocation upon assignment feature_ that is at play ? This works even if _array_ is already allocated.
> 
> - How would one go about doing this for 2D data (say a 2 column array) ?

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

```auto
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](https://stat.ethz.ch/R-manual/R-devel/library/base/html/cbind.html). The program gives output

```auto
 i1
   10 20
   11 21
 i2
   12 22
   13 23
   14 24
 combined
   10 20
   11 21
   12 22
   13 23
   14 24

```

---

_[View the full topic](https://fortran-lang.discourse.group/t/read-data-and-append-it-to-array-best-practice/1915)._
