向量中相邻元素的运算

Operations on adjacent elements in a vector

我有一个二进制向量,如果我在向量中找到 0,我想使相邻元素 0 如果它们还没有。

例如如果input = [1 1 0 1 1]我想得到output = [1 0 0 0 1]

我尝试了以下方法,但它很乱,当然还有更简洁的方法:

output=input;
for i = 1:length(input)
    if(input(i) == 0)
        output(i-1)=0;
        output(i+1)=0;
    end
end
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 = 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