布尔类型的numpy数组子矩阵求和

3

我有一个大小为11x51的布尔矩阵a。在Matlab中,我进行了一项操作,以获得大小为10x50的布尔矩阵。

a = logical(a(1:end-1,1:end-1) + a(2:end,1:end-1) + a(1:end-1,2:end) + a(2:end,2:end))

我想用Python实现这个功能。我尝试了以下代码:

a = np.zeros([11,51], dtype=bool)
a=a[0:-2,0:-2] + a[1:-1,0:-2] + a[0:-2,1:-1] + a[1:-1,1:-1]

我最终得到了一个 9x49 的矩阵,但不确定它是否进行了预期的操作。

有人能指出错误吗?


[:-2] 将删除两个元素。 - Stephen Rauch
2个回答

2

使用slicing,可以这样实现 -

a_out = (a[:-1,:-1] + a[1:,:-1] + a[:-1,1:] + a[1:,1:]).astype(bool)

由于a已经是一个布尔数组,因此我们可以跳过bool转换。

在MATLAB上的示例运行 -

>> a = logical([
    1, 1, 0, 1, 1, 0
    0, 1, 0, 0, 0, 0
    1, 1, 0, 1, 1, 1
    0, 0, 0, 0, 1, 0
    0, 0, 1, 0, 1, 1
    0, 0, 0, 1, 1, 0]);
>> a(1:end-1,1:end-1) + a(2:end,1:end-1) + a(1:end-1,2:end) + a(2:end,2:end)
ans =
     3     2     1     2     1
     3     2     1     2     2
     2     1     1     3     3
     0     1     1     2     3
     0     1     2     3     3
>> logical(a(1:end-1,1:end-1) + a(2:end,1:end-1) + ...
           a(1:end-1,2:end)   + a(2:end,2:end))
ans =
     1     1     1     1     1
     1     1     1     1     1
     1     1     1     1     1
     0     1     1     1     1
     0     1     1     1     1

在 NumPy 上运行的示例 -

In [160]: a  # Same data as in MATLAB sample
Out[160]: 
array([[ True,  True, False,  True,  True, False],
       [False,  True, False, False, False, False],
       [ True,  True, False,  True,  True,  True],
       [False, False, False, False,  True, False],
       [False, False,  True, False,  True,  True],
       [False, False, False,  True,  True, False]], dtype=bool)

In [161]: (a[:-1,:-1] + a[1:,:-1] + a[:-1,1:] + a[1:,1:])
Out[161]: 
array([[ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [False,  True,  True,  True,  True],
       [False,  True,  True,  True,  True]], dtype=bool)

1
Python中的切片与Matlab略有不同。请尝试以下Python代码:
获取除最后一个元素外的所有元素:
[:-1]

除了第一个元素以外的所有元素:
[1:]    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接