我有一个二进制向量,如果我在向量中找到0,我想将相邻元素设为0,如果它们还没有。
例如,如果输入= [1 1 0 1 1]我想得到输出= [1 0 0 0 1]
我试过……
In = [1, 1, 0, 1, 1]; % note that input is a MATLAB function already and thus a bad choice for a variable name
找到零:
ind_zeros = ~In; % or In == 0 if you want to be more explicit
现在找到前后的指标
ind_zeros_dilated = ind_zeros | [ind_zeros(2:end), false] | [false, ind_zeros(1:end-1)]
最后将邻居设置为零:
Out = In; Out(ind_zeros_dilated) = 0
为了好玩,另一种计算方法 ind_zeros_dilated 是使用卷积:
ind_zeros_dilated
ind_zeros_dilated = conv(ind_zeros*1, [1,1,1],'same') > 0 %// the `*1` is just a lazy way to cast the logical vector ind_zeros to be of type float