2D array concatenation in fortran

落爺英雄遲暮 提交于 2019-12-02 04:03:14

问题


Fortran 2003 has square bracket syntax for array concatenation, Intel fortran compiler supports it too. I wrote a simple code here for matrix concatenation:

program matrix
implicit none
real,dimension (3,3) :: mat1,mat2
real,dimension(3,6):: mat3
integer i

mat1=reshape( (/1,2,3,4,5,6,7,8,9/),(/3,3/))
mat2=reshape( (/1,2,3,4,5,6,7,8,9/),(/3,3/))
mat3=[mat1,mat2]

!display
do i=1,3,1
write(*,10) mat3(i,:)
10 format(F10.4)
end do

end program

But I get error as

mat3=[mat1,mat2]
Error: Incompatible ranks 2 and 1 in assignment

I expect the output as

1 2 3 1 2 3
4 5 6 4 5 6
7 8 9 7 8 9

Can someone comment where am I going wrong? What is rank 2 and 1 here? I guess all arrays have rank 2.


回答1:


The array concatenation in fortran 2003 doesn't work as you think. When you concatenate, it's not going to stack the two arrays side by side. It will pick elements from the first array one by one and put into a one-dimensional array. Then it will do the same thing with the second array but it will append this to the 1-D form of first array.

The following code works.

program matrix
implicit none
real,dimension (3,3) :: mat1,mat2
real,dimension(18) :: mat3
integer i

mat1=reshape( (/1,2,3,4,5,6,7,8,9/),(/3,3/))
mat2=reshape( (/1,2,3,4,5,6,7,8,9/),(/3,3/))
mat3=[mat1,mat2]

print*, shape([mat1,mat2])  !check shape of concatenated array
!display
do i=1,18,1
write(*,10) mat3(i)
10 format(F10.4)
end do

end program

However, the result you wanted can be achieved using following code

program matrix
implicit none
real,dimension (3,3) :: mat1,mat2
real,dimension(3,6) :: mat3
integer i

mat1=reshape( (/1,2,3,4,5,6,7,8,9/),(/3,3/))
mat2=reshape( (/1,2,3,4,5,6,7,8,9/),(/3,3/))

do i=1,3
mat3(i,:)=[mat1(:,i),mat2(:,i)]
enddo

!display
do i=1,3,1
write(*,*) mat3(i,:)
end do

end program



回答2:


Another way could simply be to

mat3(:,1:3) = mat1
mat3(:,4:6) = mat2

I dont know which is faster, this or the do loop above...




回答3:


Fill it using 1-D arrays then reshape your mat3.



来源:https://stackoverflow.com/questions/30928304/2d-array-concatenation-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!