计算对角块矩阵中块的坐标

时间:2015-04-04 21:51:47

标签: python numpy

我有一个对角线块matrix,我想要每个块的坐标(行,列)

a = np.zeros((25,18), dtype=int)    
a[2:8,:6]=1

a[8:13,6:12]=1

a[13:15,12:14]=1

a[15:20,14:]=1

和输出

 [(2, 0), (8, 6), (13, 12), (15, 14)]

谢谢!

2 个答案:

答案 0 :(得分:0)

我假设你的矩阵确实充满了布尔值,就像你的照片一样。

每个块都是完全正方形的,因此可以通过其起始坐标和边长来定义。另请注意,起始坐标始终位于矩阵的对角线上,因此行和列相等。

如果你看一下图片,可以清楚地看到,在每个区块的开头,紧靠上方(或左侧)的单元格为False。因此,我们可以创建一个块列表,[(坐标,长度),...],如下所示:

# Find the coordinates where each block starts
starts = []
for i in range(len(myMatrix)):
    if i==0:
        starts.append(i)
    elif not myMatrix[i,i-1]: # i.e., if the cell to the left is False
        starts.append(i)
# Get the length of each block
blocks = []
for i in range(len(starts)):
    thisStart = starts[i]
    if i == len(starts)-1:
        nextStart = len(myMatrix)
    else:
        nextStart = starts[i+1]
    length = nextStart - thisStart
    blocks.append((thisStart, length))

答案 1 :(得分:0)

如果在每个列中包含一个块或其他块,则可以通过扫描每列中的第一个非零条目并跟踪相应的行来获取每个块的坐标:

In [1]: import numpy as np
In [2]: a = np.zeros((25,18), dtype=int)    
In [3]: a[2:8,:6]=1
In [4]: a[8:13,6:12]=1
In [5]: a[13:15,12:14]=1
In [6]: a[15:20,14:]=1
In [7]: rows = set()
In [8]: blocks = []
In [9]: for col in range(a.shape[1]):
            row = np.argmax(a[:,col])
            if row not in rows:
                rows.add(row)
                blocks.append((row, col))
....:         

In [10]: blocks
Out[10]: [(2, 0), (8, 6), (13, 12), (15, 14)]