简体   繁体   English

python numpy-执行向量和矩阵加法的函数

[英]python numpy - Function to perform vector & matrix addition

I'm working on the problem which asks me: 我正在研究问我的问题:

Add two NumPy vectors or matrices together, if possible. 如果可能,将两个NumPy向量或矩阵加在一起。 If it is not possible to add the two vectors/matrices together (because their sizes differ), return False. 如果不可能将两个向量/矩阵加在一起(因为它们的大小不同),则返回False。

Here is my approach: 这是我的方法:

import numpy as np

def mat_addition(A, B):
    if A.shape != B.shape:
        return False
    else:
        return np.sum(A,B)

But when I run the code for testing, it says 但是当我运行代码进行测试时,它说

TypeError: only integer scalar arrays can be converted to a scalar index

Can someone tell me what's wrong with my code? 有人可以告诉我我的代码有什么问题吗?

np.sum can in fact be used in the way you want. 实际上, np.sum可以按您想要的方式使用。 You just need to wrap the arguments you pass to np.sum in a list: 您只需要将传递给np.sum的参数包装在一个列表中:

import numpy as np

def mat_addition(A, B):
    if A.shape != B.shape:
        return False
    else:
        return np.sum([A,B])

a = np.arange(5*3).reshape(5,3)
b = np.arange(5*3, 5*3*2).reshape(5,3)
print(mat_addition(a,b))

Output: 输出:

435

As per the numpy.sum docs, this function expects a single "array_like" object as its first argument. 根据numpy.sum文档,此函数将单个“ array_like”对象作为其第一个参数。 A list of arrays is a perfectly valid "array_like" object, so the above code works. 数组列表是一个完全有效的“ array_like”对象,因此上述代码可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM