Fortran重塑函式


下表描述了重塑函式:

函式 描述
reshape(source, shape, pad, order) 它構造一個特定形狀的形狀,從一個給定source陣列中的元素開始的陣列。如果墊不包含則soure的尺寸必須至少為產物(形狀)。如果pad包括在內,它必須具有相同的型別的soure。如果order被包括,它必須使用相同的形狀的形狀的整數陣列,值必須是一個排列(1,2,3,...,n),其中n是在形狀要素的數量,它必須小於或等於7。

範例

下面的例子演示了這一概念:

program arrayReshape
implicit none

interface
   subroutine write_matrix(a)
   real, dimension(:,:) :: a
   end subroutine write_matrix
   end interface

   real, dimension (1:9) :: b = (/ 21, 22, 23, 24, 25, 26, 27, 28, 29 /)
   real, dimension (1:3, 1:3) :: c, d, e
   real, dimension (1:4, 1:4) :: f, g, h

   integer, dimension (1:2) :: order1 = (/ 1, 2 /)
   integer, dimension (1:2) :: order2 = (/ 2, 1 /)
   real, dimension (1:16) :: pad1 = (/ -1, -2, -3, -4, -5, -6, -7, -8, &
                                 & -9, -10, -11, -12, -13, -14, -15, -16 /)

   c = reshape( b, (/ 3, 3 /) )
   call write_matrix(c)

   d = reshape( b, (/ 3, 3 /), order = order1)
   call write_matrix(d)

   e = reshape( b, (/ 3, 3 /), order = order2)
   call write_matrix(e)

   f = reshape( b, (/ 4, 4 /), pad = pad1)
   call write_matrix(f)

   g = reshape( b, (/ 4, 4 /), pad = pad1, order = order1)
   call write_matrix(g)

   h = reshape( b, (/ 4, 4 /), pad = pad1, order = order2)
   call write_matrix(h)

end program arrayReshape


subroutine write_matrix(a)
   real, dimension(:,:) :: a
   write(*,*)
   
   do i = lbound(a,1), ubound(a,1)
      write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
   end do
end subroutine write_matrix

當上述程式碼被編譯和執行時,它產生了以下結果:

21.0000000  24.0000000  27.0000000    
22.0000000  25.0000000  28.0000000    
23.0000000  26.0000000  29.0000000    

21.0000000  24.0000000  27.0000000    
22.0000000  25.0000000  28.0000000    
23.0000000  26.0000000  29.0000000    

21.0000000  22.0000000  23.0000000    
24.0000000  25.0000000  26.0000000    
27.0000000  28.0000000  29.0000000    

21.0000000  25.0000000  29.0000000   -4.00000000    
22.0000000  26.0000000  -1.00000000  -5.00000000    
23.0000000  27.0000000  -2.00000000  -6.00000000    
24.0000000  28.0000000  -3.00000000  -7.00000000    

21.0000000  25.0000000  29.0000000   -4.00000000    
22.0000000  26.0000000  -1.00000000  -5.00000000    
23.0000000  27.0000000  -2.00000000  -6.00000000    
24.0000000  28.0000000  -3.00000000  -7.00000000    

21.0000000  22.0000000  23.0000000   24.0000000    
25.0000000  26.0000000  27.0000000   28.0000000    
29.0000000  -1.00000000 -2.00000000  -3.00000000    
-4.00000000 -5.00000000 -6.00000000  -7.00000000