Find a number and range of group of the same number

조회 수: 7 (최근 30일)
Grega Mocnik
Grega Mocnik 2022년 11월 14일
댓글: Bruno Luong 2022년 11월 14일
I have an array with numbers [1 1 1 1 1 1 1 2 2 2 2 3 3 3 3 1 1 2 2 1 1 3 3 3 3 3 1 1 1 2 2 2 ]
The array has the length: of 1x42502
I would like the number of how many repeats the same number, and the range of the specific repeat.
Output example:
number 1 has 4 repeats, range of the first repeat is: 1:6, range of the second repeat is: 15:16 , etc
number 2 has 3 repeats, range ...
number 3 has 2 repeats, range ...
How to do this?
Histcounts return sum of all repeat.

답변 (2개)

Jan
Jan 2022년 11월 14일
편집: Jan 2022년 11월 14일
a = [1 1 1 1 1 1 1 2 2 2 2 3 3 3 3 1 1 2 2 1 1 3 3 3 3 3 1 1 1 2 2 2];
[b, n, idx] = RunLength(a);
idxR = [idx(:), idx(:) + n(:) - 1];
idxR = 9×2
1 7 8 11 12 15 16 17 18 19 20 21 22 26 27 29 30 32
ub = unique(b);
result = splitapply(@(c) {c}, idxR, b(:));
result = 3×1 cell array
{4×2 double} {3×2 double} {2×2 double}
result{ub(1)} % Ranges, where e.g. ub(1), which equals 1, occurs:
ans = 4×2
1 7 16 17 20 21 27 29
If you do not have a C-compiler, use RunLength_M from the same submission.

Bruno Luong
Bruno Luong 2022년 11월 14일
편집: Bruno Luong 2022년 11월 14일
A= [1 1 1 1 1 1 1 2 2 2 2 3 3 3 3 1 1 2 2 1 1 3 3 3 3 3 1 1 1 2 2 2 ];
[u,~,G]=unique(A);
n = length(u);
for g=1:n
i = find(G==g);
j = find([true; diff(i)>1; true]);
start=i(j(1:end-1));
stop=i(j(2:end)-1);
m = length(start);
fprintf('value=%g, %d intervals\n', u(g), m);
fprintf('\t(%d:%d)\n', [start, stop]');
end
value=1, 4 intervals
(1:7) (16:17) (20:21) (27:29)
value=2, 3 intervals
(8:11) (18:19) (30:32)
value=3, 2 intervals
(12:15) (22:26)
  댓글 수: 1
Bruno Luong
Bruno Luong 2022년 11월 14일
I think my approach is not good if the number of groups n is large. In this case one should use Jan's runlength.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Descriptive Statistics and Visualization에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by