Skip to main content
 首页 » 编程设计

Python之将具有不同列数的矩阵相乘

2025年05月04日47kenshinobiy

我正在尝试将两个矩阵 A 和 B 相乘,其中 B 的列数比 A 多,最好使用 python 和 numpy。

例子:

A = numpy.matrix([[2,3,15],[5,8,12],[1,13,4]], dtype=numpy.object) 
B = numpy.matrix([[2,15,6,15,8,14],[17,19,17,7,18,14],[24,14,0,24,2,11]], dtype=numpy.object) 
 
( A*B ) = [[415,297,63,411,100,235],[434,395,166,419,208,314], [319,318,227,202,250,240]] 

我找到了一些例子,如果它们是数组,但如果它们是矩阵,则没有。有人可以帮帮我吗?

请您参考如下方法:

你真的试过这个吗?它在这里工作正常:

import numpy as np 
 
def main(): 
    A = np.matrix([[2,3,15],[5,8,12],[1,13,4]], dtype=np.object) 
    B = np.matrix([[2,15,6,15,8,14],[17,19,17,7,18,14],[24,14,0,24,2,11]], dtype=np.object) 
 
    C = ( A*B ) % 26 #  = [[25,11,11,21,22,1],[18,5,10,3,0,2], [7,6,19,20,16,6]] 
    print(C) 
    return 0 
 
if __name__ == '__main__': 
    main() 

打印:

[[25 11 11 21 22 1] 
 [18 5 10 3 0 2] 
 [7 6 19 20 16 6]]