Find a number and range of group of the same number

7 次查看(过去 30 天)
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