简体   繁体   English

numpy-整个矩阵的运算

[英]numpy - operations on whole matrix

Say I have a numpy array 说我有一个numpy数组

a = np.array([[a11 a12 a13],
          [a21 a22 a23],
          [a31 a32 a33]])

I want to return the following result: 我想返回以下结果:

np.array([[a11/a1 a12/a1 a13/a1],
          [a21/a2 a22/a2 a23/a2],
          [a31/a3 a32/a3 a33/a3]])

where: 哪里:

  a1 = np.sqrt(a11**2 + a12**2 + a13**2)
  a2 = np.sqrt(a21**2 + a22**2 + a23**2)
  a3 = np.sqrt(a31**2 + a32**2 + a33**2)

In other words, I want to divide each element of the array by the norm of the row it belongs to. 换句话说,我想将数组的每个元素除以它所属行的范数。

I have written some code which does this, but it is frankly horrible - I am looping through rows of the array, which I know is not what numpy as designed for. 我已经编写了一些执行此操作的代码,但是坦率地说,这很可怕-我正在遍历数组的行,我知道这不是numpy设计的。 I have a feeling the same could be achieved by using two numpy library calls which I just don't know. 我感觉可以通过使用两个我不知道的numpy库调用来实现相同的效果。

Another thing I thought of is: 我想到的另一件事是:

a/np.reshape(np.linalg.norm(a,axis=1),(a.shape[0],1))

but I'm not sure if this is a particularly efficient way. 但我不确定这是否是一种特别有效的方法。 Any advice? 有什么建议吗?

import numpy as np

a = np.array([[11, 12, 13],
          [21, 22, 23],
          [31, 32, 33]], float)

a / np.sum(a**2, 1, keepdims=True)**0.5

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

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