Finding the min/max number of consecutive elements in an array
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
the cyclist
am 3 Sep. 2015
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?
Antworten (1)
the cyclist
am 3 Sep. 2015
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 Kommentare
Siehe auch
Kategorien
Mehr zu Data Preprocessing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!