【发布时间】:2016-09-23 08:46:12
【问题描述】:
我正在尝试在 Fortran 中编写一些需要重新排序 n 维数组的代码。我认为 reshape 内在函数结合 order 参数应该允许这样做,但是我遇到了困难。
考虑以下最小示例
program test
implicit none
real, dimension(:,:,:,:,:), allocatable :: matA, matB
integer, parameter :: n1=3, n2=5, n3=7, n4=11, n5=13
integer :: i1, i2, i3, i4, i5
allocate(matA(n1,n2,n3,n4,n5)) !Source array
allocate(matB(n3,n2,n4,n1,n5)) !Reshaped array
!Populate matA
do i5=1, n5
do i4=1, n4
do i3=1, n3
do i2=1, n2
do i1=1, n1
matA(i1,i2,i3,i4,i5) = i1+i2*10+i3*100+i4*10000+i5*1000000
enddo
enddo
enddo
enddo
enddo
print*,"Ad1 : ",matA(:,1,1,1,1),shape(matA)
matB = reshape(matA, shape(matB), order = [3,2,4,1,5])
print*,"Bd4 : ",matB(1,1,1,:,1),shape(matB) !Leading dimension of A is the fourth dimension of B
end program test
我希望这会导致
Ad1 : 1010111.00 1010112.00 1010113.00 3 5 7 11 13
Bd4 : 1010111.00 1010112.00 1010113.00 7 5 11 3 13
但我发现:
Ad1 : 1010111.00 1010112.00 1010113.00 3 5 7 11 13
Bd4 : 1010111.00 1010442.00 1020123.00 7 5 11 3 13
我已经用gfortran(4.8.3 和 4.9)和ifort(11.0)尝试了这个并找到了相同的结果,所以我很可能只是误解了 reshape 的工作原理。
任何人都可以阐明我的问题所在以及如何实现我的目标吗?
【问题讨论】:
-
您可能想要
matB的第三列,所以也许您只是没有在正确的点使用逆排列? [我认为这是你的问题,但这当然会改变你所期望的答案的其他方面。]
标签: multidimensional-array fortran reshape transpose memory-layout