MATLAB: Convert consecutive ones into alternating one/zero’s

alternatingconsecutivepuzzler

I need to convert a vector consisting of ones and zero's such that consecutive blocks of 1's will be replaced by alternating ones and zeros. Example:
[0 1 0 1 0 0 1 1 0 1 1 1 1 0 1] needs to be converted to:
[0 1 0 1 0 0 1 0 0 1 0 1 0 0 1]
Of course that can be done in a loop, but I'm looking for a vectorized way of accomplishing this. Any ideas?

Best Answer

I would be surprised to find you could beat this loop:
ii = 2;
while ii<=length(A)
if A(ii-1) && A(ii)
A(ii) = 0;
ii = ii + 2;
else
ii = ii + 1;
end
end