Find a number and range of group of the same number
8 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.
0 Commenti
Risposte (2)
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];
ub = unique(b);
result = splitapply(@(c) {c}, idxR, b(:));
result{ub(1)} % Ranges, where e.g. ub(1), which equals 1, occurs:
If you do not have a C-compiler, use RunLength_M from the same submission.
0 Commenti
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
1 Commento
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.
Vedere anche
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!