How do i find the start and end of a run of numbers?
8 views (last 30 days)
Show older comments
Leendert van Gaalen
on 2 Nov 2015
Commented: Leendert van Gaalen
on 2 Nov 2015
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.
0 Comments
Accepted Answer
Stephen23
on 2 Nov 2015
Edited: Stephen23
on 2 Nov 2015
>> 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.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!