找到2D数组的对称元素的展平索引

时间:2018-02-08 22:45:17

标签: python arrays numpy indexing

我有一个5 x 5的numpy数组:

a = np.arange(25).reshape(5, 5)

如果a被夷为平地:

 b = a.flatten()
>> [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]

我试图找到b a的对称性指数,其中对称性为a。是根据以下a = np.array([ [a, d, c, d, a], [b, e, f, e, b], [c, f, g, f, c], [b, e, f, e, b], [a, d, c, d, a] ]) 定义的:

g

元素是对称的'在约[ 0 4 20 24] [ 1 3 21 23] [ 2 10 14 22] [ 5 9 15 19] [ 6 8 16 18] [ 7 11 13 17] [12] 的正方形图案中。上面数组中显示的元素仅仅是占位符,用于显示应返回的相应索引/位置。

因此,对于给定的 n x m 数组,该函数返回所有相应的索引,如下所示:

[a a a a]
[d d d d]
[c c c c ]
... etc

其中上面的输出对应于'对称性'像这样:

model

所有的帮助都表示赞赏,提前谢谢!

2 个答案:

答案 0 :(得分:1)

我会为方形矩阵拍摄一张照片。如果您知道如何为这些情况定义对称性,那么将算法推广到非平方矩阵并不会太难。

首先,创建一个展平索引的2D数组:

ind = np.arange(a.size).reshape(a.shape)
mid = a.shape[0] // 2
odd = a.shape[0] % 2

现在创建一个沿着第三轴堆叠的垂直和水平轴翻转的上述阵列的3D数组:

idx = np.dstack([ind, np.fliplr(ind), np.flipud(ind), np.flipud(np.fliplr(ind))])
idx = idx[:mid, :mid].reshape((-1, 4)).tolist()

现在,仅当数组的大小为奇数时,找到位于中间行和列的元素:

if odd:
    idx += np.dstack([ind[:mid, mid], ind[-1:mid:-1, mid],
                      ind[mid, :mid], ind[mid, -1:mid:-1]]).reshape(-1, 4).tolist()
    idx += [[ind[mid, mid]]]

最后,如果您希望结果至少在一组索引中排序:

idx = sorted(map(sorted, idx))

然后,对于5x5数组,得到:

>>> print(idx)
[[0, 4, 20, 24],
 [1, 3, 21, 23],
 [2, 10, 14, 22],
 [5, 9, 15, 19],
 [6, 8, 16, 18],
 [7, 11, 13, 17],
 [12]]

答案 1 :(得分:0)

一个帮助你前进的提示,是你的问题是递归的。如果您知道如何查找外部方块的索引,则可以将其应用于较小的方块。

如果你能找到2d坐标[x,y]并且矩阵是n * n,那么1D当量是x * n + y

另一个提示,它仅在你的矩阵为n * n且n为奇数时才有效。尝试从中心开始,以及指数如何围绕它,然后围绕它们等...