Fortran - 操作函式



操作函式是移位函式。移位函式返回陣列形狀不變,但移動元素。

序號 函式和描述
1

cshift(array, shift, dim)

它執行迴圈移位,如果 shift 為正則向左移動 shift 個位置,如果 shift 為負則向右移動。如果 array 是向量,則以自然方式進行移位;如果它是更高秩的陣列,則沿維度 dim 的所有部分進行移位。如果省略 dim,則將其視為 1;在其他情況下,它必須是 1 到 n 之間的標量整數(其中 n 等於 array 的秩)。引數 shift 是標量整數或秩為 n-1 的整數陣列,其形狀與陣列相同,但沿維度 dim 除外(由於秩較低而被移除)。因此,不同的部分可以朝不同的方向和不同的位置數量進行移位。

2

eoshift(array, shift, boundary, dim)

它是端部移位。如果 shift 為正,則執行向左移位;如果 shift 為負,則執行向右移位。代替移出的元素,從 boundary 中獲取新元素。如果 array 是向量,則以自然方式進行移位;如果它是更高秩的陣列,則所有部分的移位沿維度 dim 進行。如果省略 dim,則將其視為 1;在其他情況下,它必須具有 1 到 n 之間的標量整數值(其中 n 等於 array 的秩)。引數 shift 是標量整數(如果 array 的秩為 1),否則它可以是標量整數或秩為 n-1 的整數陣列,其形狀與陣列 array 相同,但沿維度 dim 除外(由於秩較低而被移除)。

3

transpose (matrix)

它轉置矩陣,矩陣是秩為 2 的陣列。它替換矩陣中的行和列。

示例

以下示例演示了該概念:

program arrayShift
implicit none

   real, dimension(1:6) :: a = (/ 21.0, 22.0, 23.0, 24.0, 25.0, 26.0 /)
   real, dimension(1:6) :: x, y
   write(*,10) a
   
   x = cshift ( a, shift = 2)
   write(*,10) x
   
   y = cshift (a, shift = -2)
   write(*,10) y
   
   x = eoshift ( a, shift = 2)
   write(*,10) x
   
   y = eoshift ( a, shift = -2)
   write(*,10) y
   
   10 format(1x,6f6.1)

end program arrayShift

編譯並執行上述程式碼後,將產生以下結果:

21.0  22.0  23.0  24.0  25.0  26.0
23.0  24.0  25.0  26.0  21.0  22.0
25.0  26.0  21.0  22.0  23.0  24.0
23.0  24.0  25.0  26.0   0.0   0.0
0.0    0.0  21.0  22.0  23.0  24.0

示例

以下示例演示了矩陣的轉置:

program matrixTranspose
implicit none

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

   integer, dimension(3,3) :: a, b
   integer :: i, j
    
   do i = 1, 3
      do j = 1, 3
         a(i, j) = i
      end do
   end do
   
   print *, 'Matrix Transpose: A Matrix'
   
   call write_matrix(a)
   b = transpose(a)
   print *, 'Transposed Matrix:'
   
   call write_matrix(b)
end program matrixTranspose


subroutine write_matrix(a)

   integer, 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

編譯並執行上述程式碼後,將產生以下結果:

Matrix Transpose: A Matrix

1  1  1
2  2  2
3  3  3
Transposed Matrix:

1  2  3
1  2  3
1  2  3
fortran_arrays.htm
廣告

© . All rights reserved.