Borrar filtros
Borrar filtros

How to count numbers considering all consecutives as one??

1 visualización (últimos 30 días)
Hi, I need to count some numbers like: Data=2, 3, 4, 7,8 9, 10, 20,25,27; Now, counting should be: 2,3,4=1; 7,8,9,10=1; 20=1; 25=1; 27=1; Total count=5 (1+1+1+1+1) i.e. consecutive numbers should be count as one together and any individual value should be one. Any help regarding matlab programming would be highly appreciated. Thanks in advance. Badrul

Respuesta aceptada

Shashank Prasanna
Shashank Prasanna el 20 de En. de 2013
Editada: Shashank Prasanna el 20 de En. de 2013
Data=[2, 3, 4, 7,8 9, 10, 20,25,27];
sum = 1; % The first set is counted.
for i = 2:length(Data)
if Data(i)~=Data(i-1)+1
%Data(i)
sum=sum+1;
end
end
disp(sum)
  3 comentarios
Azzi Abdelmalek
Azzi Abdelmalek el 20 de En. de 2013
Don't use sum and i as variables. sum is the function that sums the elements of an array, and i is used to represent complex numbers
Shashank Prasanna
Shashank Prasanna el 20 de En. de 2013
Azzi, Its perfectly fine to use them since MATLAB gives the highest precedence to variables before function names. Avoid them if you plan to use these function in your program or just clear the variables right before you want to use the function:
However as you mentioned it is safer to avoid using them.

Iniciar sesión para comentar.

Más respuestas (2)

Cedric
Cedric el 20 de En. de 2013
Editada: Cedric el 20 de En. de 2013
Here is a funny way to achieve this:
>> sum(diff(Data)>1)+1
EDIT: see my comment after Azzi's remark.
  6 comentarios
Azzi Abdelmalek
Azzi Abdelmalek el 20 de En. de 2013
It still dont work. Look at this example.
Data=[1 2 3 4 7 8 7 6 2 1]
I suggest
sum(diff(Data)~=0 & diff(Data)~=1)+1
Cedric
Cedric el 20 de En. de 2013
Well, the OP will pick the one that matches his requirements I guess; I don't test Data(i+1)==Data(i)+1 (consec. elements are consec. integers) in my solutions, but Data(i)==Data(j)+1 for |i-j|=1 (ordered neighbors are consec. integers).

Iniciar sesión para comentar.


Roger Stafford
Roger Stafford el 20 de En. de 2013
count = sum([true,diff(data)~=0]);

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by