Is there a way to sum a matrix entry and it's reflection across a diagonal along a given axis in a numpy array?

好久不见. 提交于 2021-02-08 10:30:48

问题


Suppose

A = np.array([[1,2,0,3,5,0,0],[5,6,7,0,9,5,10]])

(The actual data set in this case is a square matrix with a shifted diagonal of zeros) I want to create an np array V that sums the pairs reflected across the first zero in each row, in the order of their distance from the zero. i.e., V[0]=[(2+3),(1+5),0] V[1] =[(7+9),(6+5),(10+5)]...

So

V = ([5,6,0],[16,11,15])

I can accomplish this in a very rudimentary way by looping through each row and then adding each row to a shifted version of its reflection, with just two rows it would be something simple like this.

B = A.copy()
B = B[...,::-1]
V = np.array([A[0]+np.roll(B[0],-2),A[1]+B[1]])[:,0:3]

However I'm wondering if there is a vectorized approach to this operation, or some function native to numpy that sums an entry of an array along with its reflection across its diagonal because as the data set gets large this becomes less efficient.

来源:https://stackoverflow.com/questions/64408577/is-there-a-way-to-sum-a-matrix-entry-and-its-reflection-across-a-diagonal-along

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!