MATLAB: Create vector containing longest consecutive array of different vector

longest consecutive number vector

How can I build a vector B with the longest consectutive array of vector A which has multiple consecutive numbers (e.g.[2 5 6 7 10 12 13 20])? In this example the answer should be B= 5 6 7

Best Answer

  • Assuming that the input A is a row-vector containing integer values, then try this:
    >> A = [2,5,6,7,10,12,13,20];
    >> X = diff([0,diff(A)==1,0]);
    >> Y = [-find(X>0);find(X<0)];
    >> [~,Z] = max(sum(Y));
    >> A(-Y(1,Z):Y(2,Z))
    ans = 5 6 7
    Note that if there are multiple groups of consecutive numbers of the same length then it will return the first group only. Also note that it will generate an error if A contains fewer than two elements.