首页 > 解决方案 > Python中NxM的矩阵乘法

问题描述

我在 Python 中有 2 个矩阵:形状为 (4,1) 的矩阵 A 和形状为 (4,4) 的矩阵 B。我使用列表中的数据形成了 2 个矩阵。

valList 数据看起来像

00200030
00200030
00200030
00200030
00480051
FFF0004B
FFF0004B

我将每个项目转换为 32 位整数,然后使用数据形成矩阵。

for item in valList:
    int(item,32)

B_RC = createMatrix(rows,1,valList)
B = np.array(B_RC)
print B

A_RC = valList[rows:rows + (rows * cols)]
A = np.array(A_RC).reshape( (rows,cols))
print A

def createMatrix(rowCount, colCount, dataList):   
    mat = []
    for i in range (rowCount):
        rowList = []
        for j in range (colCount):
            if dataList[j] not in mat:
                rowList.append(dataList[i])
        mat.append(rowList)

    return mat

我想将这两个矩阵相乘。我使用了 numpy,但下面的代码出现以下错误:

>>> C=np.matmul(B,A)

error: ufunc 'matmul' did not contain a loop with signature matching types dtype('S8') dtype('S8') dtype('S8')

我应该使用什么功能?

标签: pythonnumpymatrixmatrix-multiplication

解决方案


Python 为这些用例提供了运算符:

A * B  # dot-product
A @ B  # matrix-multiplication

矩阵乘法运算符是右结合的。

如果您需要这些作为函数参数:

import operator
operator.matmul(A, B)

推荐阅读