Numpy 广播数组
我在 NumPy 中有以下数组:
A = array([1, 2, 3])
如何获取以下矩阵(没有显式循环)?
B = [ 1 1 1
2 2 2
3 3 3 ]
C = [ 1 2 3
1 2 3
1 2 3 ]
谢谢!
I have the following array in NumPy:
A = array([1, 2, 3])
How can I obtain the following matrices (without an explicit loop)?
B = [ 1 1 1
2 2 2
3 3 3 ]
C = [ 1 2 3
1 2 3
1 2 3 ]
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Edit2:OP在评论中询问如何计算
我可以想到两种方法。我喜欢这种方式,因为它很容易概括:
这个想法是使用 np.ogrid。这定义了两个 numpy 数组的列表,一个形状为 (3,1),另一个形状为 (1,3):
grid[0]
可以用作索引的代理我
,和grid[1]
可以用作索引j
的代理。因此,在表达式
l(i, i) + l(j, j) - 2 * l(i, j)
中的任何地方,您只需替换i
-->;grid[0]
和j
-->grid[1]
,而 numpy 广播则负责剩下的工作:然而,在这个例子中特殊情况,由于
l(i,i)
和l(j,j)
只是l
的对角线元素,因此您可以这样做相反:d[np.newaxis,:]
将d
的形状提升为 (1,3),并且d[:,np.newaxis]
将d
的形状提升为 (3,1)。Numpy 广播将
d[np.newaxis,:]
和d[:,np.newaxis]
泵送到形状 (3,3),并根据需要复制值。Edit1:通常您不需要形成
B
或C
。 Numpy 广播的目的是允许您使用A
代替B
或C
。如果您向我们展示您计划如何使用B
或C
,我们也许能够向您展示如何使用A
和 numpy 进行相同的操作广播。(原始答案):
或
来自肮脏伎俩部门:
但请注意,这些是
A
的视图,而不是副本(如上面的解决方案)。改变B
,改变A
:Edit2: The OP asks in the comments how to compute
I can think of two ways. I like this way because it generalizes easily:
The idea is to use
np.ogrid
. This defines a list of two numpy arrays, one of shape (3,1) and one of shape (1,3):grid[0]
can be used as a proxy for the indexi
, andgrid[1]
can be used as a proxy for the indexj
.So everywhere in the expression
l(i, i) + l(j, j) - 2 * l(i, j)
, you simply replacei
-->grid[0]
, andj
-->grid[1]
, and numpy broadcasting takes care of the rest:However, in this particular case, since
l(i,i)
andl(j,j)
are just the diagonal elements ofl
, you could do this instead:d[np.newaxis,:]
pumps up the shape ofd
to (1,3), andd[:,np.newaxis]
pumps up the shape ofd
to (3,1).Numpy broadcasting pumps up
d[np.newaxis,:]
andd[:,np.newaxis]
to shape (3,3), copying values as appropriate.Edit1: Usually you do not need to form
B
orC
. The purpose of Numpy broadcasting is to allow you to useA
in place ofB
orC
. If you show us how you plan to useB
orC
, we might be able to show you how to do the same withA
and numpy broadcasting.(Original answer):
or
From the dirty tricks department:
But note that these are views of
A
, not copies (as were the solutions above). ChangingB
, altersA
:非常旧的线程,但以防万一有人关心......
Very old thread but just in case someone cares...