Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

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

조회 수: 1 (최근 30일)
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.

답변 (1개)

Guillaume
Guillaume 2016년 5월 10일
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'}))

이 질문은 마감되었습니다.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by