在numpy中创建有效的数组(Efficient array creation in numpy)

编程入门 行业动态 更新时间:2024-10-09 14:22:53
在numpy中创建有效的数组(Efficient array creation in numpy)

我正在尝试创建一个三维数组,Tusing numpy定义如下:

T_ {i,j,k} = \ delta_ {i,k} - \ delta {j,k}

其中\ delta_ {i,j}是Kronecker delta函数(当i = j时为1,否则为0)。 我想知道用numpy做这个最有效的方法。 我可以使用for循环创建两个三维数组并将其减去。 但我怀疑有一种更快更自然的方法。 非常感激任何的帮助。

I am trying to create a three dimensional array, Tusing numpy defined as follows:

T_{i, j, k} = \delta_{i, k} - \delta{j, k}

where \delta_{i, j} is the Kronecker delta function (1 when i=j and 0 otherwise). I am wondering what the most efficient way to do this using numpy. I can create two three dimensional arrays using for loops and subtract them. But I suspect there is a quicker and more idiomatic method. Any help would be most appreciated.

最满意答案

相当于三角洲的eye是裸eye :

delta = numpy.eye(5) T = delta[:,None,:] - delta[None,:,:]

None创建了一个用于numpy广播的<virtual>维度(不需要额外的内存)。

The equivalent to delta is eye in numpy:

delta = numpy.eye(5) T = delta[:,None,:] - delta[None,:,:]

The None creates a ‹virtual› dimension (doesn't take any additional memory) used for broadcasting in numpy.

更多推荐

本文发布于:2023-08-02 08:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1372754.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   numpy   Efficient   creation   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!