How do i find the start and end of a run of numbers?

8 views (last 30 days)
Hi all,
I would like to know to find the start and end of run of numbers in a matrix. I would like to end up with a matrix with the start and end indices of the run of numbers and if there is no run of numbers I would like to know that as well :).
for example
input:
x = 1 3 4 5 6 7 8 9 10 13 14 16 17
output:
y= 1 1,
2 9,
10 11,
12 13,
I was trying the following code but this doesn't do the trick :(
j = 1;
for i= 1:length(x)
counter = 0;
%start of 'run'
y(j,1) = i;
while x(i+counter) == counter+i+1
counter= counter+1;
end
%eind of 'run'
y(j,2) = i+counter;
i=i+counter;
j = j+1;
end
hope you can help. Thanx in advance.

Accepted Answer

Stephen23
Stephen23 on 2 Nov 2015
Edited: Stephen23 on 2 Nov 2015
Use diff and find instead of using a loop:
>> x = [1,3,4,5,6,7,8,9,10,13,14,16,17];
>> D = diff(x)~=1;
>> y = [find([true,D])',find([D,true])']
y =
1 1
2 9
10 11
12 13
If you want to use MATLAB efficiently then learn how to write vectorized code instead of using loops to solve every little task. MATLAB is a high-level language.
  1 Comment
Leendert van Gaalen
Leendert van Gaalen on 2 Nov 2015
Hi Stephen, Thanx! Knowing all these functions helps a lot and working with MATLAB will help me get better at it and learn more functions. I will definately look into the vectorized coding.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!