生成两个NumPy数组的矩阵乘积

生成两个NumPy数组的矩阵乘积

我们可以用函数np.matmul(a,b)将两个矩阵相乘。当我们将两个顺序为(mn)和(pq)的数组相乘以得到矩阵乘积时,其输出包含m行和q列,其中n是n==p的一个必要条件。

语法: numpy.matmul( x1 , x2 , / , out=None , * , casting=’same_kind’ , order=’K’ , dtype=None , subok=True [, signature , extobj ])

两个矩阵相乘,从第一个数组的行和第二个数组的列中取出相应的元素进行相乘。然后将数值相加,得出最终答案。假设有两个矩阵A和B。

A = [[A00, A01],
     [A10, A11]]

B = [[B00, B01],
     [B10, B11]]

Then the product is calculated as shown below
A*B = [[(A00*B00 + A01*B10), (A00*B01 + A01*B11)],
       [(A10*B00 + A11+B10), (A10*B01 + A11*B11)]]

以下是实施情况。

# Importing Library
import numpy as np
  
# Finding the matrix product
arr1 = np.array([[1, 2, 3], [4, 5, 6],
                 [7, 8, 9]])
arr2 = np.array([[11, 12, 13], [14, 15, 16],
                 [17, 18, 19]])
  
matrix_product = np.matmul(arr1, arr2)
print("Matrix Product is ")
print(matrix_product)
print()
  
arr1 = np.array([[2,2],[3,3]])
arr2 = np.array([[1,2,3],[4,5,6]])
  
matrix_product = np.matmul(arr1, arr2)
print("Matrix Product is ")
print(matrix_product)
print()
  
arr1 = np.array([[100,200],[300,400]])
arr2 = np.array([[1,2],[4,6]])
  
matrix_product = np.matmul(arr1, arr2)
print("Matrix Product is ")
print(matrix_product)

输出:

Matrix Product is 
[[ 90  96 102]
 [216 231 246]
 [342 366 390]]

Matrix Product is 
[[10 14 18]
 [15 21 27]]

Matrix Product is 
[[ 900 1400]
 [1900 3000]]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程