matlab - How to extract vectors of consecutive numbers? -
suppose have q vector defined q = [1 2 3 4 5 8 9 10 15];
, find way extract different vectors of consecutive numbers , vector rest of elements. result like:
q1 = [1 2 3 4 5]; q2 = [8 9 10 ]; q3 = [15];
you can using diff
, cumsum
, accumarray
:
q = accumarray(cumsum([1, diff(q)~=1])', q', [], @(x){x})
which returns:
{[1,2,3,4,5]; [8,9,10]; [15]}
i.e. q{1}
gives [1,2,3,4,5]
etc far cleaner solution having separately named vectors. if really wanted have them, , know how many groups out, can follows:
[q1,q2,q3] = q{:};
explanation:
accumarray
apply aggregation function (4th input) elements of vector (2nd input) based on groupings specified in vector (1st input).
to use notation in docs:
sub = cumsum([1, diff(q)~=1])'; val = q'; fun = @(x){x};
note sub
needs start 1
. idea use diff
find elements consecutive (i.e. q(i+1) - q(i) == 1
) vectorized using diff
function. specifying diff(q)~=1
can find breaks between groups of consecutive numbers (concatenating 1
@ beginning force break @ start). cumsum
converts these breaks vector of in right form sub
i.e.
sub = [1 1 1 1 1 2 2 2 3]
the aggregation function specify cell concatenation.
Comments
Post a Comment