给定两个矩阵,请打印这些矩阵的乘积

时间:2019-08-03 10:44:48

标签: python matrix-multiplication

我必须检查给定的矩阵是否可以相乘,如果是,则返回乘积。 我无法使用numpy来计算乘积。

使用的示例:

A = [[1,2],[3,4]]
B = [[1,2,3,4,5],[5,6,7,8,9]]

预期输出:A*B = [[11,14,17,20,23],[23,30,37, 44,51]]

这是我的代码和输出:

def matrix_mult(A,B):
    countA = 0
    countB = 0
    result = [[0]*len(B[0])]*len(A)
    for i in range(len(A)):
        if A[i][1]:
            countA += 1

    for i in range(len(B)):
        if B:
            countB += 1

    if countA == countB:
        for i in range(len(A)):
            for j in range(len(B[0])):
                for k in range(len(A)):
                    result[i][j] += A[i][k]*B[k][j]

    return result

A = [[1,2],[3,4]]
B = [[1,2,3,4,5], [5,6,7,8,9]]
matrix_mult(A,B)

输出:

[[34, 44, 54, 64, 74], [34, 44, 54, 64, 74]]

代码/逻辑是否有问题?

3 个答案:

答案 0 :(得分:2)

有罪是您的<input type="number" v-model.number="f.credit" :disabled="f.debit > 0"> 声明。这不是通过复制元素来声明列表的好方法(而不是创建适当的矩阵)。更多详细信息in this discussion

尝试:

result

代替:

result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]

那应该很好!

答案 1 :(得分:1)

为什么要使代码这么长?你可以试试这个-

ctlUSBHID.dll

看看这是否对您有帮助。

答案 2 :(得分:1)

我建议使用numpy:

import numpy as np

A = np.array([[1,2],[3,4]])
B = np.array([[1,2,3,4,5],[5,6,7,8,9]])

np.matmul(A, B)

# output : array([[11, 14, 17, 20, 23],
#                 [23, 30, 37, 44, 51]])

与您的代码有关的几个问题,下面是我试图改善您的代码的问题:

def matrix_mult(A,B):

    num_col_a = len(A[0])
    num_rows_b = len(B)

    result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]

    if num_col_a == num_rows_b:
        for row_a_index, row_a in enumerate(A):
            for col_index, col_b in enumerate(zip(*B)):
                result[row_a_index][col_index] = sum(a * b for a, b in zip(row_a, col_b))

    return result

A = [[1,2],[3,4]]
B = [[1,2,3,4,5], [5,6,7,8,9]]
print(matrix_mult(A,B))

# output: [[11, 14, 17, 20, 23], [23, 30, 37, 44, 51]]