Question

For a project, I'm trying to find the first 1 of a series of ones in a vector. For example, I have as input:

x1=[1 0 0 1 1 1 0 1 0 1 0 0 1 1]

and I need as output:

Y1=[1 0 0 1 0 0 0 1 0 1 0 0 1 0]

So every time there is a 1 in the vector, all consequent ones need to be turned into zeroes.

I have the following code, but for some reason it just returns Y1 with exactly the same values as x1.

n=numel(x1);
Y1=zeros(n,1);
for i = 1:n
if x1(i) == 1
    Y1(i)= 1;
    for j = (i+1): n 
        if x1(j)== 1
            Y1(j)=0;
        elseif x1(j) == 0
            Y1(j)=0;
            i=j+1;
            break
        end
    end
elseif x1(i) == 0
    Y1(i)= 0;
end

end

Any help would be greatly appreciated.

Was it helpful?

Solution

Easy with diff. No loops needed.

Y1 = [ x1(1) diff(x1)==1 ];

or equivalently

Y1 = diff([0 x1])==1;

How this works: diff computes the difference of an element with respect to the preceding element. When that difference is 1, a new run of ones has begun. The first element requires special treatment.

OTHER TIPS

A generalization of the answer by @Luis for the case where your vectors don't just contain zeros and ones:

Y1 = diff([0 x1]) & x1 == 1

This checks whether the value is one, and whether it is different from the previous value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top