我想写一个Matlab脚本。 在我的例子中,我有一个向量A = [1 3 4 5 7 8 9 10 11 13 14 15 16 17 19 20 21]
现在我想在缺少数字的位置自动剪切矢量(这里缺少数字2,6,12,18)。
结果我想要载体[1]和[3 4 5]和[7 8 9 10 11]和[13 14 15 16 17]和[19 20 21]。因此,您可以看到新的向量具有不同的长度。
我想过使用for循环,但我不知道如何编写这些新的向量。
感谢您的帮助:)
答案 0 :(得分:2)
这是一种方法:
s = [find(diff(A(:).')>1) numel(A)]; %'// detect where consecutive difference exceeds 1
s = [s(1) diff(s)]; %// sizes of groups
result = mat2cell(A(:).', 1, s); %'// split into cells according to those sizes
在你的例子中,这给出了
>> celldisp(result)
result{1} =
1
result{2} =
3 4 5
result{3} =
7 8 9 10 11
result{4} =
13 14 15 16 17
result{5} =
19 20 21
另一种方法(以不同方式计算组大小):
s = diff([0 sum(bsxfun(@lt, A(:), setdiff(1:max(A(:).'), A(:).')), 1) numel(A)]);
result = mat2cell(A(:).', 1, s);
答案 1 :(得分:2)
包含diff
,cumsum
& accumarray
-
out = accumarray(cumsum([0 ; diff(A(:))~=1])+1,A(:),[],@(x) {x})
示例运行 -
>> A
A =
1 3 4 5 7 8 9 10 ...
11 13 14 15 16 17 19 20 21
>> celldisp(out)
out{1} =
1
out{2} =
3
4
5
out{3} =
7
8
9
10
11
out{4} =
13
14
15
16
17
out{5} =
19
20
21