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

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 Comments

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?
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).

Sign in to comment.

Answers (1)

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).

Categories

Asked:

on 3 Sep 2015

Answered:

on 3 Sep 2015

Community Treasure Hunt

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

Start Hunting!