Python:获得一个矩阵,该基质包含来自另一个矩阵的所有元素之间的所有差异
我需要计算给定矩阵的元素的所有组合之间的所有差异(以绝对值为单位)。例如,给定一些矩阵m
,例如
M = [[1 2]
[5 8]]
我需要获得一个矩阵x
定义为
X = [[1 4 7]
[1, 3, 6]
[4, 3, 3]
[7, 6, 3]]
我将每一行与m
和每列及其来自其他元素的缩写(除了自身之外)。我一直在尝试为 cicles做一些,但是我无法获得与我想要的东西的接近。
在我的代码中,我使用了numpy,从而定义了所有矩阵,
M = np.zeros([nx, ny])
然后随着代码的进展而替换值,例如
M[i, j] = 5
I need to calculate all differences (in absolute value) between all combinations of the elements from a given matrix. For example, given some matrix M
such as
M = [[1 2]
[5 8]]
I need to obtain a matrix X
defined as
X = [[1 4 7]
[1, 3, 6]
[4, 3, 3]
[7, 6, 3]]
where I associated each row to each element in M
and each column with its substraction from every other element (except with itself). I've been trying to make some for
cicles, but I haven't been able to get something close to what I want.
In my code, I used numpy, thus defining all the matrices as
M = np.zeros([nx, ny])
and then replacing the values as the code progresses such as
M[i, j] = 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然可以通过循环浏览元素来轻松完成,但这是一种更快,更具Pythonic的方式。
使用此处建议的方法如何获得numpy数组的非对角性元素的索引?
While this can be easily done by looping over elements, here is a faster and more pythonic way.
Removal of diagonal elements was done using approach suggested here How to get indices of non-diagonal elements of a numpy array?
与 @wizzzz1的非常好的答案相同,但使用更简单的语法和更快的执行:
输出:
Sensibly the same approach as the very good answer of @wizzzz1, but with a simpler syntax and faster execution:
Output: