Search code examples
matlabvectoroperations

Operations on adjacent elements in a vector


I have a binary vector, if I find a 0 in the vector I want to make the adjacent elements 0 if they are not already.

For example if input = [1 1 0 1 1] I want to get output = [1 0 0 0 1]

I tried the following but it's messy and surely there is a neater way:

output=input;
for i = 1:length(input)
    if(input(i) == 0)
        output(i-1)=0;
        output(i+1)=0;
    end
end

Solution

  • In = [1, 1, 0, 1, 1];  % note that input is a MATLAB function already and thus a bad choice for a variable name
    

    Find the zeros:

    ind_zeros = ~In;  % or In == 0 if you want to be more explicit
    

    now find the indicies before and after

    ind_zeros_dilated = ind_zeros | [ind_zeros(2:end), false] | [false, ind_zeros(1:end-1)]
    

    Finally set the neighbours to zero:

    Out = In;
    Out(ind_zeros_dilated) = 0
    

    For fun, an alternative way to calculate ind_zeros_dilated is to use convolution:

    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