Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Consecutive Numbers

255 views
Skip to first unread message

Nichola

unread,
May 13, 2009, 11:56:01 AM5/13/09
to
Hi. Given a series of sorted numbers, is there a function in MATLAB that recognizes the consecutive values?

For example:
1, 2, 3, 4, 5, 10, 11, 13
Should be divided into:
1:5
10:11
13

I've written a function that goes over the values and compares the number before and after a certain element, but I'm quite sure there's a faster and better way.

Thanks a lot.

Matt Fig

unread,
May 13, 2009, 12:11:01 PM5/13/09
to
Look at:
x = [1 2 3 4 5 10 11 13];

D = ~~([1 diff(x - (1:length(x)))]) % Where are the ones?

Nichola

unread,
May 13, 2009, 12:23:02 PM5/13/09
to
"Matt Fig" <spam...@yahoo.com> wrote in message <guerel$ei0$1...@fred.mathworks.com>...

> Look at:
> x = [1 2 3 4 5 10 11 13];
>
> D = ~~([1 diff(x - (1:length(x)))]) % Where are the ones?

Thanks. I see your point, but could you please explain the ~~ for me? Thanks.

Matt Fig

unread,
May 13, 2009, 12:31:01 PM5/13/09
to
"Nichola " <abdon...@gmail.com> wrote in message
> Thanks. I see your point, but could you please explain the ~~ for me? Thanks.

This makes D a logical vector. Actually this is not strictly necessary, depending on how you would proceed from here. I might do something like this:


x = [1 2 3 4 5 10 11 13 14]
F = diff(find([1 diff(x - (1:length(x)))]));
mat2cell(x,1,[F length(x)-sum(F)])

kanna...@gmail.com

unread,
Jun 10, 2009, 3:37:40 PM6/10/09
to
Thanks very much

Siyi

unread,
Jun 10, 2009, 4:36:48 PM6/10/09
to

Essentially the same method as Matt's but a oneliner:

mat2cell(x,1,diff([0,find(diff(x) ~= 1),length(x)]))

Bruno Luong

unread,
Jun 11, 2009, 2:45:02 AM6/11/09
to
Or using SplitVec on FEX: http://www.mathworks.com/matlabcentral/fileexchange/24255

>> a=[1, 2, 3, 4, 5, 10, 11, 13]

a =

1 2 3 4 5 10 11 13

>> SplitVec(a,'consecutive')

ans =

[1x5 double] [1x2 double] [13]

% Bruno

Sprinceana

unread,
Jun 11, 2009, 3:51:02 AM6/11/09
to
"Nichola " <abdon...@gmail.com> wrote in message <gues56$10v$1...@fred.mathworks.com>...

>>help ops

PopV Visitkul

unread,
Jul 9, 2009, 6:40:17 AM7/9/09
to
Hi Matt,

Would it be possible to explain the principle behind the code by any chance please? What I really like about it is that it managed to group the consecutive numbers really nicely in a large file. What I am trying to do now is grouping bunches of zeros and ones from a random mixture of zeros and ones sequence. I slightly modified your code for do it yesterday. However it seems to only group the the zeros together while leaving all the ones ungrouped. This is because i didn't know what i was doing. Your explanation would be highly appreciated.

Many thanks,
Viput


"Matt Fig" <spam...@yahoo.com> wrote in message <guesk5$19s$1...@fred.mathworks.com>...

0 new messages