如何使用fortran的扩展函数来逐块而不是按列复制数组?

时间:2013-09-12 19:29:47

标签: fortran

例如,此代码:

program sandbox
    implicit none
    real, dimension(2, 2) :: p
    p = reshape((/ 1, 3, 2, 4 /), shape(p))

    print *, spread(P, 2, 2)

end program sandbox

返回此数组:

1 1 2 2
3 3 4 4

但我正试图让它归还“

1 2 1 2
3 4 3 4

这可以使用spread吗?实际上,它需要被推广,因为我可能正在生成像

这样的矩阵
1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4

取决于编译时我不知道的其他变量。

1 个答案:

答案 0 :(得分:4)

试试这个(除[ ]符号代替(/ /)之外,所有内容都在Fortran 90标准中

program sandbox
   implicit none
   real, dimension(2, 2) :: p
   real, dimension(2, 4) :: q
   integer i

   print *, "p"
   p = reshape([1, 3, 2, 4], shape(p))
   do i=1, 2
      print *, p(i, :)
   end do

   print *, "spread (orig)"
   q = reshape(spread(p, 2, 2), [2, 4])
   do i=1, 2
      print *, q(i, :)
   end do

   print *, "spread"
   q = reshape(spread(transpose(p), 2, 2), [2, 4], order=[2, 1])
   do i=1, 2
      print *, q(i, :)
   end do

   print *, "[p, p]"
   q = reshape([p, p], [2, 4])
   do i=1, 2
      print *, q(i, :)
   end do
end program sandbox