MATLAB: How many consecutive ones

homeworkloopsmatlab functionrecursion

Write a function ConsecutiveOnes to detect in a logical row array of any length the locations the length of the ones sequences. If there is a single one, the location of the one should be indicated with a length of one. For example, for the input array [0 0 1 1 0 0 1] the function ConsecutiveOnes produces the output [0 0 2 0 0 0 1]; for the input array [0,0,1,1,0,0,0,1,1,1] the function ConsecutiveOnes produces the output [0 0 2 0 0 0 0 3 0 0]
I am trying a recursion function, which should be sth like
for i = 1:a
function indicator = solve(inputArray1(i))
I know this expression is wrong, but I wonder how to display an idea like this.

Best Answer

out = double(diff([~A(1);A(:)]) == 1);
v = accumarray(cumsum(out).*A(:)+1,1);
out(out == 1) = v(2:end);
or
out = zeros(size(A));
ii = strfind([0,A(:)'],[0 1]);
out(ii) = strfind([A(:)',0],[1 0]) - ii + 1;