identifying and isolating consecutive numbers
2 次查看(过去 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 ]
assert(size(A,1)==1 && isa(A,'double'));
p=find(diff(A)>1);
ind=[A(1),A(p+1);A(p),A(end)]
% 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
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{:}
1 个评论
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)])
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!