0

我是 python 新手,我正在编写一个矩阵程序,但是有一个问题我不知道如何获得正确的输出,我需要帮助。这就是问题:给定一个 nXn 矩阵 A 和一个 kXn 矩阵 B 找到 AB 。这就是我到目前为止所拥有的。先感谢您

def matrixmult (A, B):
    rows_A = len(A)
    cols_A = len(A[0])
    rows_B = len(B)
    cols_B = len(B[0])

    if cols_A != rows_B:
      print "Cannot multiply the two matrices. Incorrect dimensions."
      return

    # Create the result matrix
    # Dimensions would be rows_A x cols_B
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    print C

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k]*B[k][j]
    return C
4

3 回答 3

1

你的功能:

def matrixmult (A, B):
    rows_A = len(A)
    cols_A = len(A[0])
    rows_B = len(B)
    cols_B = len(B[0])

    if cols_A != rows_B:
      print "Cannot multiply the two matrices. Incorrect dimensions."
      return

    # Create the result matrix
    # Dimensions would be rows_A x cols_B
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    print C

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k]*B[k][j]
    return C

这似乎与此功能相同。

如果我运行这个:

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

print matrixmult(matrix, matrix)    # that is your function...

它返回:

[[30, 36, 42], [66, 81, 96], [102, 126, 150]]

这与 Numpy 相同:

import numpy as np

a=np.array(matrix)
b=np.array(matrix)
print np.dot(a,b)
#  [[ 30  36  42]
    [ 66  81  96]
    [102 126 150]]

与矩阵乘法相同,更简洁地说:

def mult(mtx_a,mtx_b):
    tpos_b = zip( *mtx_b)
    rtn = [[ sum( ea*eb for ea,eb in zip(a,b)) for b in tpos_b] for a in mtx_a]
    return rtn

所以——问题可能出在你的输入数据上。

于 2013-04-01T04:28:50.490 回答
0

使用 numPy 库来解决您的问题。

将 numpy 导入为 np

x = np.array( ((2,3), (3, 5)) )

y = np.array( ((1,2), (5, -1)) )

打印 x * y

数组([[ 2, 6], [15, -5]])

更多示例: http: //www.python-course.eu/matrix_arithmetic.php

下载 numPy: http ://scipy.org/Download

于 2013-04-01T02:33:03.780 回答
0

一个班轮:

def matrixmult(m1, m2):
    return [
        [sum(x * y for x, y in zip(m1_r, m2_c)) for m2_c in zip(*m2)] for m1_r in m1
    ]

解释:

zip(*m2) - 从第二个矩阵中获取一列

zip(m1_r, m2_c) - 从 m1 行和 m2 列创建元组

sum(...) - 对乘法行求和 * col

测试:

m1 = [[1, 2, 3], [4, 5, 6]]
m2 = [[7, 8], [9, 10], [11, 12]]
result = matrixmult(m1, m2)
assert result == [[58, 64], [139, 154]]
于 2019-01-26T15:18:47.203 回答