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!