Effacer les filtres
Effacer les filtres

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

3 vues (au cours des 30 derniers jours)
Eli Dim
Eli Dim le 3 Sep 2015
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 commentaires
the cyclist
the cyclist le 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?
Eli Dim
Eli Dim le 3 Sep 2015
Modifié(e) : Eli Dim le 3 Sep 2015
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).

Connectez-vous pour commenter.

Réponses (1)

the cyclist
the cyclist le 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).

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by