【问题标题】:Triangular indices for multidimensional arrays in numpynumpy中多维数组的三角索引
【发布时间】:2015-03-04 13:48:46
【问题描述】:

我们知道np.triu_indices 返回一个矩阵的三角形上部的索引,一个二维数组。

如果想像下面的代码那样创建索引怎么办?

indices = []
for i in range(0,n):
    for j in range(i+1,n):
        for k in range(j+1,n):
            indices.append([i,j,k])

以 num-pythonic 的方式?

【问题讨论】:

  • 您查看过triu 的代码吗?可能是 Python,没有编译。

标签: python numpy numerical-methods


【解决方案1】:

一般情况下,您可以获得一个索引列表,这些索引遵循您使用的代码的逻辑

from itertools import combinations
ndim = 3 # number of dimensions
n = 5 # dimension's length (assuming equal length in each dimension)

indices = list(combinations(range(n), r=ndim)

或者如果你想遍历每个位置:

for i,j,k in combinations(range(n), r=ndim):
    # Do your cool stuff here
    pass

但是,您将其称为多维矩阵的三角形上部。我不确定它的定义是什么,并试图用嵌套循环可视化您选择的索引我无法弄清楚......(我现在只是好奇是否有多维三角矩阵的定义: -P)

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

a = zip(*indices)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(a[0], a[1], a[2])
plt.xlabel('x')
plt.ylabel('y')
plt.show()

(我移动了视角以尝试显示选择了哪些位置)

【讨论】:

    猜你喜欢
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 2020-03-25
    • 2019-01-04
    • 2018-01-22
    相关资源
    最近更新 更多