我有(在 python 中)以下操作(对矩阵和向量使用 numpy):
result = (A.dot(input)/b)
使用A 矩阵和b,input 向量。 A和b是固定的,input是变化的。因此,我想将 A 和 b 简化为单个元素,向量或矩阵,然后可以通过乘法或点积与输入向量组合.可惜我不会写
result = (A/b).dot(input)
之后会产生错误的值。我怎样才能将 A 和 b 连接成一个元素?
请您参考如下方法:
使用 None/np.newaxis 将 b 扩展为 2D然后将 A 除以它:
Ab = A/b[:,None]
然后通过矩阵乘法在这些迭代中重复使用 Ab,其中您将 input 作为唯一变量:
Ab.dot(input)
作为旁注,尽量避免变量名也是 Python 内置函数名,在本例中是 input。
sample 运行-
In [164]: A = np.random.rand(4,5)
In [165]: input1 = np.random.rand(5)
In [166]: b = np.random.rand(4)
In [167]: (A.dot(input1)/b)
Out[167]: array([ 2.80446671, 4.49821539, 3.73365285, 1.83176278])
In [168]: Ab = A/b[:,None]
In [169]: Ab.dot(input1)
Out[169]: array([ 2.80446671, 4.49821539, 3.73365285, 1.83176278])
