用numpy中不同形状的矩阵做加法和乘法

2024-04-18 01:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个N*M的矩阵A和一个N长度的向量V,我想做一个+V,其中A行I中的每个元素和V中的元素I求和,怎么做?你知道吗

例如:

A = np.random.rand(3,2)
V = np.array([1,2,3])
A + V

ValueError: operands could not be broadcast together with shapes (3,2) (3) 

我想做同样的乘法和除法。你知道吗


Tags: 元素withnpnot矩阵randombearray
3条回答

这里要查找的概念是broadcasting。它使您能够在任意两个矩阵之间进行逐点交互,只要它们的形状对应,或者在没有对应的轴上,至少有一个边退化,即大小为1。在您的例子中,您需要向V添加一个轴

A + V[:, np.newaxis]

您需要告诉numpy它必须将向量的维数V扩展1,您可以使用特殊索引np.newaxis来完成。它看起来是这样的:

import numpy as np

A = np.array([[10,20],[100,200],[1000,2000]])
V = np.array([1,2,3])
A + V[:,np.newaxis]

array([[  11,   21],
       [ 102,  202],
       [1003, 2003]])

slicing docs

Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension. The added dimension is the position of the newaxis object in the selection tuple.

解决方案:

V = V.reshape(-1,1)
A + V

现在可以了

相关问题 更多 >

    热门问题