Finding the min/max number of consecutive elements in an array
6 ビュー (過去 30 日間)
古いコメントを表示
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
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?
回答 (1 件)
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).
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Data Preprocessing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!