Find a number and range of group of the same number

8 visualizzazioni (ultimi 30 giorni)
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.

Risposte (2)

Jan
Jan il 14 Nov 2022
Modificato: Jan il 14 Nov 2022
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 il 14 Nov 2022
Modificato: Bruno Luong il 14 Nov 2022
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 Commento
Bruno Luong
Bruno Luong il 14 Nov 2022
I think my approach is not good if the number of groups n is large. In this case one should use Jan's runlength.

Accedi per commentare.

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by