Start/stop values for blocks of consecutive numbers

主宰稳场 提交于 2019-12-22 07:09:07

问题


If I have a vector of:

[4,5,6,7,11,12,13,14,21,22,23]

How can I, without a loop, extract the start/end values of all consecutive number blocks i.e. the desired result for the above vector would be a 2-column vector:

b = 

4   7
11  14
21  23

回答1:


Easy:

a = [4,5,6,7,11,12,13,14,21,22,23];
b = reshape(a(sort([find(a - circshift(a,[0,1]) ~= 1),find(a - circshift(a,[0,-1]) ~= -1)])),2,[])'

Output:

b =

 4     7
11    14
21    23



回答2:


Another approach:

x = [4,5,6,7,11,12,13,14,21,22,23];
x = x(:);
ind = find([1; diff(x)-1; 1]);
result = [x(ind(1:end-1)) x(ind(2:end)-1)];



回答3:


Like this:

    v  = [4,5,6,7,11,12,13,14,21,22,23];

    dv = diff(diff(v)==1);

    bv = find(dv==+1)+1;
    if dv(1) == 0
            bv = [1,bv];
    end;

    ev = find(dv==-1)+1;
    if dv(end) == 0
            ev = [ev,numel(v)];
    end;

    b = v([bv(:),ev(:)]);



回答4:


Not the best answer, but I spend a hour to get it, so I want to post it:

x = (0:10:a(end))'; %'
subindex = @(A) [A(1) A(end)];
fun = @(q) subindex( a(a>q & a<q+10));
res = cell2mat(arrayfun(fun, x, 'UniformOutput', false));

It works for any size of a.



来源:https://stackoverflow.com/questions/34041857/start-stop-values-for-blocks-of-consecutive-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!