Effacer les filtres
Effacer les filtres

identifying and isolating consecutive numbers

1 vue (au cours des 30 derniers jours)
Katerina F
Katerina F le 16 Fév 2024
Modifié(e) : Matt J le 17 Fév 2024
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 commentaire
Walter Roberson
Walter Roberson le 16 Fév 2024
That code is not producing that error?

Connectez-vous pour commenter.

Réponse acceptée

Matt J
Matt J le 16 Fév 2024
Modifié(e) : Matt J le 17 Fév 2024
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 commentaire
Dyuman Joshi
Dyuman Joshi le 17 Fév 2024
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]}

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by