Finding longest consecutive numbers in array

40 Ansichten (letzte 30 Tage)
John Doe
John Doe am 27 Jan. 2018
Kommentiert: Martina am 24 Okt. 2025 um 15:10
Hello everyone,
This is somewhat of a silly question but I can't seem to figure it out. If I have an array of numbers what I want is to find the location of my longest consecutive numbers for example:
my arrary = [ 1999 2000 2001 2003 2004 2005 2006 2007];
I want my output to be = [ 4 5 6 7 8]; because that's the location of my longest consecutive numbers (2003-2007). I tried to find where difference is equal to 1 but then the result is [1 1 1 0 1 1 1 1] , it doesn't take the position of the last number which is 2007 here and even if I fix that problem also I'd still have to find the locations for the longest consecutive one's for the second scenario.
I could use some help in this,
Thank You!!!

Akzeptierte Antwort

Stephen23
Stephen23 am 27 Jan. 2018
Bearbeitet: Stephen23 am 24 Okt. 2025 um 14:45
V = [1999,2000,2001,2003,2004,2005,2006,2007];
D = diff([0;diff(V(:))==1;0]);
B = find(D>0);
E = find(D<0);
[~,idx] = max(E-B);
idy = B(idx):E(idx)
idy = 1×5
4 5 6 7 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  4 Kommentare
Stephen23
Stephen23 am 24 Okt. 2025 um 14:44
Bearbeitet: Stephen23 am 24 Okt. 2025 um 14:49
@Martina: well spotted! I made a few changes, please check it!
longestConsecutive([2001,2002,2003,2004,2005,2006,2007,2009,2010]) % 1:7
ans = 1×7
1 2 3 4 5 6 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
longestConsecutive([1999,2001,2003,2004,2005,2006,2007,2009,2010]) % 3:7
ans = 1×5
3 4 5 6 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
longestConsecutive([1999,2001,2003,2004,2005,2006,2007,2008,2009]) % 3:9
ans = 1×7
3 4 5 6 7 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
longestConsecutive([2001,2002,2003,2004,2005,2006,2007,2008,2009]) % 1:9
ans = 1×9
1 2 3 4 5 6 7 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
longestConsecutive([2001,2003,2005,2007]) % none
ans = 1×0 empty double row vector
function idy = longestConsecutive(inp)
D = diff([0;diff(inp(:))==1;0]);
B = find(D>0);
E = find(D<0);
[~,idx] = max(E-B);
idy = B(idx):E(idx);
end
As an alternative you could use something from FEX, for example
on the DIFF() of the vector.
Martina
Martina am 24 Okt. 2025 um 15:10
Thank you so much!! <3

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Kategorien

Mehr zu MATLAB Report Generator 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!

Translated by