Fortran - 向量和矩阵乘法函数


下表描述了向量和矩阵乘法函数:

功能 描述
点积(向量a,向量b) 此函数返回两个输入向量的标量积,这两个输入向量必须具有相同的长度。
matmul(矩阵_a,矩阵_b) 它返回两个矩阵的矩阵乘积,该矩阵必须一致,即具有 (m, k) 和 (k, n) 等维度

例子

以下示例演示了点积:

program arrayDotProduct

   real, dimension(5) :: a, b
   integer:: i, asize, bsize
   
   asize = size(a)
   bsize = size(b)
   
   do i = 1, asize
      a(i) = i
   end do
   
   do i = 1, bsize
      b(i) = i*2
   end do
   
   do i = 1, asize
      Print *, a(i)
   end do
   
   do i = 1, bsize
      Print *, b(i)
   end do
   
   Print*, 'Vector Multiplication: Dot Product:'
   Print*, dot_product(a, b)
   
end program arrayDotProduct

当上面的代码被编译并执行时,会产生以下结果:

1.00000000    
2.00000000    
3.00000000    
4.00000000    
5.00000000    
2.00000000    
4.00000000    
6.00000000    
8.00000000    
10.0000000    
Vector Multiplication: Dot Product:
110.000000   

例子

以下示例演示了矩阵乘法:

program matMulProduct

   integer, dimension(3,3) :: a, b, c
   integer :: i, j
    
   do i = 1, 3
      do j = 1, 3
         a(i, j) = i+j
      end do
   end do
   
   print *, 'Matrix Multiplication: A Matrix'
   
   do i = 1, 3
      do j = 1, 3
         print*, a(i, j)
      end do
   end do
   
   do i = 1, 3
      do j = 1, 3
         b(i, j) = i*j
      end do
   end do
   
   Print*, 'Matrix Multiplication: B Matrix'
   
   do i = 1, 3
      do j = 1, 3
         print*, b(i, j)
      end do
   end do
   
   c = matmul(a, b)
   Print*, 'Matrix Multiplication: Result Matrix'
   
   do i = 1, 3
      do j = 1, 3
         print*, c(i, j)
      end do
   end do
   
end program matMulProduct

当上面的代码被编译并执行时,会产生以下结果:

Matrix Multiplication: A Matrix
2
3
4
3
4
5
4
5
6
 Matrix Multiplication: B Matrix
1
2
3
2
4
6
3
6
9
Matrix Multiplication: Result Matrix
20
40
60
26
52
78
32
64
96
fortran_arrays.htm