问题描述
Fortran 2003对数组连接有方括号语法,英特尔fortran编译器也支持它。我在这里写了一个简单的代码,用于矩阵连接: 程序矩阵
隐式无
实数,维( 3,3):: mat1,mat2
real,dimension(3,6):: mat3
整数
$ b $ mat1 =重塑((/ 1,2,3, 4,5,6,7,8,9 /),(/ 3,3 /))
mat2 =重塑((/ 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格式(F10.4)
结束做
结束程序
但是我得到的错误是:
mat3 = [mat1,mat2 ]
错误:在赋值中不兼容的等级2和1
我期望输出为
1 2 3 1 2 3
4 5 6 4 5 6
7 8 9 7 8 9
有人可以评论我哪里错了吗?这里的等级2和1是什么?我猜所有数组的排名都是2。
Fortran 2003中的数组串联并不像您想象的那样工作。当你连接时,它不会并排堆叠两个数组。它会从第一个数组中逐个拾取元素并放入一维数组中。然后它会对第二个数组做同样的事情,但它会将其附加到第一个数组的一维形式。
下面的代码有效。程序矩阵
隐式无
实数,维(3,3):: mat1,mat2
real ,尺寸(18):: mat3
整数i
mat1 =重塑((/ 1,2,3,4,5,6,7,8,9 /),(/ 3,3 /))
mat2 =重塑((/ 1,2,3,4,5,6,7,8,9 /),(/ 3,3 /))
mat3 = [mat1,mat2]
print *,shape([mat1,mat2])!检查连接数组的形状
!display
do i = 1,18,1
写(*,10)mat3(i)
10格式(F10.4)
结束做
结束程序
然而,您想要的结果可以使用以下代码来实现:
程序矩阵
隐式无
实数,维(3,3):: mat1,mat2
实数,维(3,6):: mat3
整数i
mat1 =重塑((/ 1,2,3,4,5,6,7,8,9 /),(/ 3,3 /))
mat2 =重塑( (/ 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
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.
解决方案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
这篇关于Fortran中的二维数组串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!