使用print打印产品矩阵时出现问题

时间:2019-11-16 14:46:13

标签: python arrays function matrix

我有一个矩阵A和B,我想要这两个矩阵的乘积。这是我在python中的代码。

import numpy as np

def matrix_multiplication(a: np.ndarray, b: np.ndarray) -> np.ndarray:

    n, m_a = a.shape
    m_b, p = b.shape

    c = np.zeros((n, p))

    if m_a != m_b:
        raise ValueError('Dimensions of the Matrix A and B are not compatable.')
    else:
        for i in range(len(0, a.shape)):
            for j in range(len(0, a.shape[0])):
                for k in range(0, len(b.shape)):
                    c += a[i][j] * b[j][k]

                    print(c)
                    return c

但是,当我运行代码时,我得到的是“进程以退出代码0完成”,而不是矩阵C。这里可能出什么问题了?

2 个答案:

答案 0 :(得分:0)

似乎您正在尝试制作点积,如果是这样,则有一个内置的numpy函数可以为您完成此操作。

import numpy as np

def matrix_multiplication(a: np.ndarray, b: np.ndarray) -> np.ndarray:
    return a.dot(b)

a = np.array([[1, 2], [3, 4]])
b = np.array([[2, 4], [6, 8]])

print (matrix_multiplication(a, b))

或更短:

import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[2, 4], [6, 8]])

print (a.dot(b))

答案 1 :(得分:0)

import numpy as np

def matrix_multiplication(a: np.ndarray, b: np.ndarray) -> np.ndarray:

    n, m_a = a.shape
    m_b, p = b.shape

    c = np.zeros((n, p))

    if m_a != m_b:
        raise ValueError('Dimensions of the Matrix A and B are not compatable.')

    else:
        for i in range(a.shape[0]):
            for j in range(len(b[0])):
                for k in range(b.shape[0]):
                    c[i][j] += a[i][k] * b[k][j]
    return c


a = np.array([[28,3], [3, 4],[8,9]])
b = np.array([[6, 4,7], [6, 8,9]])

print (matrix_multiplication(a, b))