Python:获得一个矩阵,该基质包含来自另一个矩阵的所有元素之间的所有差异

发布于 2025-01-22 07:01:51 字数 464 浏览 2 评论 0原文

我需要计算给定矩阵的元素的所有组合之间的所有差异(以绝对值为单位)。例如,给定一些矩阵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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

剪不断理还乱 2025-01-29 07:01:51

虽然可以通过循环浏览元素来轻松完成,但这是一种更快,更具Pythonic的方式。

import numpy as np

M = np.array([[1,2],[5,8]])

# flatten M matrix
flatM = M.reshape(-1) 

# get all pairwise differences
X = flatM[:,None] - flatM[None,:]

# remove diagonal elements, since you don't want differences between same elements
mask = np.where(~np.eye(X.shape[0],dtype=bool))
X = X[mask]

# reshape X into desired form
X = X.reshape(len(flatM),-1)

# take absolute values
X = np.abs(X)

print(X)

使用此处建议的方法如何获得numpy数组的非对角性元素的索引?

While this can be easily done by looping over elements, here is a faster and more pythonic way.

import numpy as np

M = np.array([[1,2],[5,8]])

# flatten M matrix
flatM = M.reshape(-1) 

# get all pairwise differences
X = flatM[:,None] - flatM[None,:]

# remove diagonal elements, since you don't want differences between same elements
mask = np.where(~np.eye(X.shape[0],dtype=bool))
X = X[mask]

# reshape X into desired form
X = X.reshape(len(flatM),-1)

# take absolute values
X = np.abs(X)

print(X)

Removal of diagonal elements was done using approach suggested here How to get indices of non-diagonal elements of a numpy array?

長街聽風 2025-01-29 07:01:51

与 @wizzzz1的非常好的答案相同,但使用更简单的语法和更快的执行:

a = M.ravel()
X = (abs(a-a[:, None])
     [~np.eye(M.size, dtype=bool)]
     .reshape(-1, M.size-1)
     )

输出:

array([[1, 4, 7],
       [1, 3, 6],
       [4, 3, 3],
       [7, 6, 3]])

Sensibly the same approach as the very good answer of @wizzzz1, but with a simpler syntax and faster execution:

a = M.ravel()
X = (abs(a-a[:, None])
     [~np.eye(M.size, dtype=bool)]
     .reshape(-1, M.size-1)
     )

Output:

array([[1, 4, 7],
       [1, 3, 6],
       [4, 3, 3],
       [7, 6, 3]])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文