Search code examples
matlab

How to count consecutive 0's in between values of 1 in MATLAB?


there's a question that asks for a given vector that contains 1's and 0's, return a vector that gives the number of 0's in between each one. For example: input = [0 1 0 0 0 1 0 1 1 1 0 0 0 1 0 1 1 0 0] output = [1 3 1 0 0 3 1 0 2]

my code:

function y = count_zero(x)
y = []
count = 0
for i = 1:length(x)
if x(i) == 0
count = count +1
elseif x(i) == 1
count = 0
end
y = horzcat(y,count)
end 
end

I know that my code is wrong, but I couldn't find a way to modify this code to solve the problem


Solution

  • You should only append to y when you hit the next 1, not for each element in x. You can achieve that by moving the concatenation within the elseif, but then you also need to do it right at the end to handle the final element

    You should use indentation to make your code more readable and semi-colons at the end of each line to suppress command line output.

    function y = count_zero(x)
    y = [];
    count = 0;
    for i = 1:length(x)
        if x(i) == 0
            count = count +1;
        elseif x(i) == 1
            y = horzcat(y,count);
            count = 0;
        end
    end
    y = horzcat(y,count);
    

    If you wanted a short way to do this, you could find the indices where x==1 (appending a 1 to the start and end of x to handle the edge cases) and then take the difference between those indices. The number of zeros is one less than the diff of the indices.

    y = diff(find([1,x,1]==1))-1;