필터 지우기
필터 지우기

Finding the min/max number of consecutive elements in an array

조회 수: 3 (최근 30일)
Eli Dim
Eli Dim 2015년 9월 3일
답변: the cyclist 2015년 9월 3일
I have an example vector (attached). I need to find the min and max number of consecutive elements in this vector. How can I do this without a for loop?
  댓글 수: 2
the cyclist
the cyclist 2015년 9월 3일
Your question is not very clear to me. Do you mean the min/max number of consecutive elements that are equal to each other?
For example, for the vector
v = [7 6 6 6 6 6 8 8];
would you want the min to be 1 and the max to be 5? Or something else?
Eli Dim
Eli Dim 2015년 9월 3일
편집: Eli Dim 2015년 9월 3일
Sorry if I was unclear. An example of the vector looks like this:
vector = [2569,2570,2571,2574,2575,2576,2577,2578,2590,2600,2601];
My goal is to find the minimum number of consecutive elements. In this case the result should be 1 (2590). If I have the vector vector1:
vector1 = [2569,2570,2571,2574,2575,2576,2577,2578,2600,2601];
The result should be 2 (2600,2601). Also, for the maximum number of consecutive elements, for vector and vector1, the answer should be 5 (2574-2578). All my vector entries are non-zero numbers which are indices (so there are no repetition of any entries in the vector).

댓글을 달려면 로그인하십시오.

답변 (1개)

the cyclist
the cyclist 2015년 9월 3일
I believe this code will do what you want. I suggest you do some thorough testing, though.
vector = [2569,2570,2571,2574,2575,2576,2577,2578,2590,2600,2601];
vector = sort(vector); % You can remove this line if you are certain the vector is sorted already.
d = diff(vector);
minRun = numel(d)+1;
maxRun = 1;
currentRun = 1;
for i = 1:numel(d);
if d(i)==1
currentRun = currentRun + 1;
maxRun = max(maxRun,currentRun);
else
minRun = min(minRun,currentRun);
currentRun = 1;
end
end
Conceptually, what this code is doing is assuming that the maximum run is length 1, until it runs through the vector and proves otherwise. Similarly, it assumes that the minimum run is the entire vector, unless it proves otherwise.
If your vectors are very large, there are probably smarter ways to do this. For example, the File Exchange has some contributions that calculate run length efficiently (e.g. this one).

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by