identifying and isolating consecutive numbers

2 ビュー (過去 30 日間)
Katerina F
Katerina F 2024 年 2 月 16 日
編集済み: Matt J 2024 年 2 月 17 日
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
  1 件のコメント
Walter Roberson
Walter Roberson 2024 年 2 月 16 日
That code is not producing that error?

サインインしてコメントする。

採用された回答

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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by