我有一个11×51布尔矩阵a.为此,我在Matlab中执行此操作以获得大小为10×50的布尔矩阵.
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]
我最终得到了9×49矩阵,但不确定它是否正在执行预期的操作.
有人可以指出错误吗?
解决方法:
使用slicing,它将是-
a_out = (a[:-1,:-1] + a[1:,:-1] + a[:-1,1:] + a[1:,1:]).astype(bool)
由于a已经是布尔数组,因此我们可以跳过布尔转换.
在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)
标签:matrix,arrays,matlab,python,numpy