MATLAB: Putting Consecutive numbers into variables

consecutive numbers

I data in this format a=[1;2;3;7;0;6;7;8;9;2;4;3;14;15;16;17;0;9;2];
what I need to accomplish is to put consecutive numbers into different variables…
in this case the expected outcome is a1=[1;2;3]; a2=[6;7;8;9]; a3=[14;15;16;17]; How do I

Best Answer

  • >> A = [1;2;3;7;0;6;7;8;9;2;4;3;14;15;16;17;0;9;2];
    >> D = diff([false;diff(A(:))==1;false]);
    >> F = @(b,e)A(b:e);
    >> C = arrayfun(F,find(D>0),find(D<0),'UniformOutput',false);
    >> C{:}
    ans =
    1
    2
    3
    ans =
    6
    7
    8
    9
    ans =
    14
    15
    16
    17
    You can access the data in the cell array C using basic indexing: