MATLAB: Finding longest consecutive numbers in array

arrayconsecutivematlab helpnoobnumbers

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!!!

Best Answer

If you have the Image Processing Toolbox you can use bwareafilt() along with diff() and do it like this:
myarray = [1999 2000 2001 2003 2004 2005 2006 2007]
result = find(bwareafilt([0, diff(myarray)] == 1, 1)) % Returns [5,6,7,8]
result = [result(1)-1, result] % Prepend right most element index 4.
You see:
myarray =
1999 2000 2001 2003 2004 2005 2006 2007
result =
5 6 7 8
result =
4 5 6 7 8