陣列操作

由於其計算目標,陣列上的數學運算在 Fortran 中是直截了當的。

加減

對相同形狀和大小的陣列的操作與矩陣代數非常相似。可以編寫加法(和減法)來代替用迴圈遍歷所有索引:

real, dimension(2,3) :: A, B, C
real, dimension(5,6,3) :: D
A    = 3.    ! Assigning single value to the whole array
B    = 5.    ! Equivalent writing for assignment
C    = A + B ! All elements of C now have value 8.
D    = A + B ! Compiler will raise an error. The shapes and dimensions are not the same

切片中的陣列也是有效的:

integer::i, j
real, dimension(3,2) :: Mat = 0.
real, dimension(3)   :: Vec1 = 0., Vec2 = 0., Vec3 = 0.
i = 0
j = 0
do i = 1,3
  do j = 1,2
    Mat(i,j) = i+j
  enddo
enddo
Vec1 = Mat(:,1)
Vec2 = Mat(:,2)
Vec3 = Mat(1:2,1) + Mat(2:3,2)

功能

以同樣的方式,假設元件操作(儘管這不是系統的),大多數內部函式可以隱式使用:

real, dimension(2) :: A, B
A(1) = 6
A(2) = 44 ! Random values
B    = sin(A) ! Identical to B(1) = sin(6), B(2) = sin(44).

乘法和除法

必須注意產品和分工:使用*/符號的內在操作是逐個元素的:

real, dimension(2) :: A, B, C
A(1) = 2
A(2) = 4
B(1) = 1
B(2) = 3
C = A*B ! Returns C(1) = 2*1 and C(2) = 4*3

這絕不能與矩陣運算相混淆(見下文)。

矩陣運算

矩陣運算是內在程式。例如,上一節陣列的矩陣乘積如下:

real, dimension(2,1) :: A, B
real, dimension(1,1) :: C
A(1) = 2
A(2) = 4
B(1) = 1
B(2) = 3
C = matmul(transpose(A),B) ! Returns the scalar product of vectors A and B

複雜操作允許通過建立臨時陣列來封裝函式。雖然有些編譯器和編譯選項允許,但不建議這樣做。例如,可以編寫包含矩陣轉置的產品:

real, dimension(3,3) :: A, B, C
A(:) = 4
B(:) = 5
C = matmul(transpose(A),matmul(B,matmul(A,transpose(B)))) ! Equivalent to A^t.B.A.B^T