Classify numbers in a vector

2 visualizaciones (últimos 30 días)
Thomas
Thomas el 22 de En. de 2016
Editada: Stephen23 el 22 de En. de 2016
Hello, I got a problem when dealing with numbers classifying in a vector. Problem is like that:
With a vector A = [1 2 3 4 5 9 10 13 15 17 18 19 21 24];
I try to separate the consecutive series and non-consecutive series so that I am able to have outputs like:
a=[1 2 3 4 5]
b=[9 10]
c=[13]
d=[15]
..etc
I tried diff() and regexp (), but I still can't solve it.
If anyone can help, it would be greatly appreciated.
Thank you!

Respuesta aceptada

Stephen23
Stephen23 el 22 de En. de 2016
Editada: Stephen23 el 22 de En. de 2016
Here is a simple solution in just two lines:
>> A = [1 2 3 4 5 9 10 13 15 17 18 19 21 22 24 25];
>> idx = find([true,1~=diff(A),true]);
>> out = arrayfun(@(x,y)A(x:y),idx(1:end-1),idx(2:end)-1,'UniformOutput',false);
>> out{:}
ans =
1 2 3 4 5
ans =
9 10
ans =
13
ans =
15
ans =
17 18 19
ans =
21 22
ans =
24 25

Más respuestas (1)

Azzi Abdelmalek
Azzi Abdelmalek el 22 de En. de 2016
Editada: Azzi Abdelmalek el 22 de En. de 2016
A = [8 1 2 3 4 5 9 10 13 15 17 18 19 21 22 24 25];
ii=[1 diff(A)];
idx1=[1 find(ii~=1)];
idx2=[idx1(2:end)-1 numel(A)];
out=arrayfun(@(x,y) A(x:y),idx1,idx2,'un',0);
celldisp(out)

Categorías

Más información sobre R Language en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by