How to count numbers considering all consecutives as one??
이전 댓글 표시
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
채택된 답변
추가 답변 (2개)
Here is a funny way to achieve this:
>> sum(diff(Data)>1)+1
EDIT: see my comment after Azzi's remark.
댓글 수: 6
Mohammad
2013년 1월 20일
Azzi Abdelmalek
2013년 1월 20일
편집: Azzi Abdelmalek
2013년 1월 20일
Cedric, it don't work if Data is not sorted
I assumed Data(i+1)>=Data(i) from the wording of the statement, but you are right, without this assumption that would be:
sum(abs(diff(data))>1)+1
I also assumed that two equal numbers do not break a group. If it is not the case the expression is:
sum(abs(diff(data))~=1)+1
Mohammad
2013년 1월 20일
Azzi Abdelmalek
2013년 1월 20일
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
2013년 1월 20일
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).
Roger Stafford
2013년 1월 20일
count = sum([true,diff(data)~=0]);
카테고리
도움말 센터 및 File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!