Info

This question is closed. Reopen it to edit or answer.

How do i find the index from a logical array that meets the condition, without using for loop?

1 view (last 30 days)
I would like to find the minimum index i from a logical array a such that n consecutive elements starting from i are all 1. For example: a=[1 0 1 1 1 0 1 1 1 1], if n=1 return i=1; if n=2 or 3,then return i=3; if n=4 then return i=7. I don't want to use for loop.

Answers (1)

Guillaume
Guillaume on 10 May 2016
This is a classic run length encoding problem, there are several functions that calculate that for you on the FileExchange and plenty of answers on this forum. Alternatively, a combination of diff and find is all you need:
a = [1 0 1 1 1 0 1 1 1 1]
%find location and lengths of runs
transitions = diff([0 a 0]);
runstarts = find(transitions == 1);
runpastends = find(transitions == -1);
runlengths = runpastends - runstarts;
%display
sortrows(table(runlengths', runstarts', 'VariableNames', {'length', 'start'}))

This question is closed.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!