gpt4 book ai didi

python - bool numpy 数组的子矩阵求和

转载 作者:太空宇宙 更新时间:2023-11-03 15:55:07 24 4
gpt4 key购买 nike

我有一个 11x51 bool 矩阵 a。为此,我在 Matlab 中执行此操作以获得大小为 10x50 的 bool 矩阵。

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 矩阵,但我不确定它是否在执行预期的操作。

谁能指出错误?

最佳答案

使用 slicing , 这将是 -

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

因为 a 已经是一个 bool 数组,我们可以跳过 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)

关于python - bool numpy 数组的子矩阵求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43836252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com