1

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
Dan
  • 45,079
  • 17
  • 88
  • 157
Hefaestion
  • 203
  • 1
  • 8

1 Answers1

3
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
Dan
  • 45,079
  • 17
  • 88
  • 157
  • 1
    This is a great answer, far better than my attempt! I am sure that avoid "input" as a function will save me hours of debugging in future, thank you very much! – Hefaestion May 25 '16 at 12:37