numpy中多维数组的三角索引 [英] Triangular indices for multidimensional arrays in numpy

查看:121
本文介绍了numpy中多维数组的三角索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We know that np.triu_indices returns the indices of the triangular upper part of a matrix, an array with two dimensions.

如果要按以下代码创建索引怎么办?

What if one wants to create indices as in the following code?

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的方式?

in a num-pythonic way?

推荐答案

通常,您可以获得遵循您所放置代码逻辑的索引列表

In general you can get a list of indexes that follow the logic of the code you put with

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)

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

or if you want to iterate over each position:

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


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


However, you referred to it as the triangular upper part of a multidimensional matrix. I'm not sure what's the definition of it, and trying to visualize the indexes you selected with your nested loops I can't figure it out... (I'm just curious now on if there's a deffinition for multidimensional triangular matrix :-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()

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

(I moved the view angle to try to show what positions are selected)

这篇关于numpy中多维数组的三角索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆