identifying and isolating consecutive numbers

1 次查看(过去 30 天)
I found the following questions in Matlab which is similar to mine
I have a vector, for example, A= [1 2 3 4 14 15 23 24 25 ]
and I want a code that will identify regions of consecutive numbers and separate them into their own array. ie, a code that will split A into
B = [1 2 3 4] C = [14 15] D = [23 24 25]
I would like this code to be able to work on a matrix A of variable length. Any suggestions?
..................I tryed an answer that worked in the first place but then was giviing me an error. The answer and the error are below
MATLAB ANSWER:
A= [1 2 3 4 14 15 23 24 25 ]
A = 1x9
1 2 3 4 14 15 23 24 25
assert(size(A,1)==1 && isa(A,'double'));
p=find(diff(A)>1);
ind=[A(1),A(p+1);A(p),A(end)]
ind = 2x3
1 14 23 4 15 25
% ind =
% 1 14 23
% 4 15 25
ERROR
Operands to the logical AND (&&) and OR (||) operators must be convertible to
logical scalar values. Use the ANY or ALL functions to reduce operands to logical
scalar values.
...
What could I do to rectify please? Thanks

采纳的回答

Matt J
Matt J 2024-2-16
编辑:Matt J 2024-2-17
code that will split A into B = [1 2 3 4] C = [14 15] D = [23 24 25]
It would be a bad idea to split A into separate variables, but you can split it in cell array form as follows:
A= [1 2 3 4 14 15 23 24 25 ];
D=find( diff([A,inf])~=1 );
Asplit=mat2cell(A,1,[D(1), diff(D) ] ) ; %the final result
Asplit{:}
ans = 1×4
1 2 3 4
ans = 1×2
14 15
ans = 1×3
23 24 25
  1 个评论
Dyuman Joshi
Dyuman Joshi 2024-2-17
A similar approach -
A = [1 2 3 4 14 15 23 24 25];
idx = [find(diff(A)~=1) numel(A)];
out = mat2cell(A, 1, [idx(1) diff(idx)])
out = 1x3 cell array
{[1 2 3 4]} {[14 15]} {[23 24 25]}

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by