仅使用广播从矩阵的指定列向量中减去列向量 [英] Subtract a column vector from matrix at specified vector of columns using only broadcast

查看:120
本文介绍了仅使用广播从矩阵的指定列向量中减去列向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用另一个向量从numpy矩阵中减去列向量,该向量是需要从主矩阵中减去第一个列向量的列的索引.例如.

I want to subtract a column vector from a numpy matrix using another vector which is index of columns where the first column vector needs to be subtracted from the main matrix. For eg.

M = array([[  1,   2,   1,   1],
           [  2,   1,   1,   1],
           [  1,   1,   2,   1],
           [  2,   1,   1,   1],
           [  1,   1,   1,   2]])  # An example matrix

V = array([1, 1, 1, 1, 1]) # An example column vector

I = array([0, 3, 2, 3, 1, 3, 3]) # The index maxtrix

现在我想在I中给定的列号上从M中减去V. 例如. I [0]为0,因此从矩阵M的第一列(零索引)中减去V.

Now I want to subtract V from M at column numbers given in I. For eg. I[0] is 0, so subtract V from first column (zero index) of matrix M.

类似地,I [1] = 3,从矩阵M的第四列(三个索引)中减去V.

Similarly I[1] = 3, subtract V from fourth column (three index) of matrix M.

操作结束时,由于3在I中出现4次,因此将从第三列中减去V,即M-4的最后一列.

At the end of operation, since 3 occurs 4 times in I, so V will be subtracted from third column i.e. last column of M- 4 times.

我只需要广播,不循环就可以做到这一点.

I need to do this using only broadcast, no loops.

我尝试了以下操作:

M[:, I] - V[np.newaxis, :].T

但是它最终广播的结果矩阵的列数比M中的列数还要多.

but it ends up broadcasting resultant matrix to have more columns than there are in M.

推荐答案

一个人可以使用bincountouter

>>> M - np.outer(V, np.bincount(I, None, M.shape[1]))
array([[ 0,  1,  0, -3],
       [ 1,  0,  0, -3],
       [ 0,  0,  1, -3],
       [ 1,  0,  0, -3],
       [ 0,  0,  0, -2]])

subtract.at

>>> out = M.copy()
>>> np.subtract.at(out, (np.s_[:], I), V[:, None])
>>> out
array([[ 0,  1,  0, -3],
       [ 1,  0,  0, -3],
       [ 0,  0,  1, -3],
       [ 1,  0,  0, -3],
       [ 0,  0,  0, -2]])

这篇关于仅使用广播从矩阵的指定列向量中减去列向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆