如果我有一个矢量:
[4,5,6,7,11,12,13,14,21,22,23]
如何,没有循环,提取所有连续数字块的开始/结束值,即上述向量的所需结果将是2列向量:
b =
4 7
11 14
21 23
答案 0 :(得分:4)
另一种方法:
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)];
答案 1 :(得分:3)
易:
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,[])'
输出:
b =
4 7
11 14
21 23
答案 2 :(得分:2)
像这样:
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(:)]);
答案 3 :(得分:2)
不是最好的答案,但我花了一个小时才得到它,所以我想发布它:
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));
适用于任何大小的a
。