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.
0 个评论
回答(2 个)
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];
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 个评论
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
1 个评论
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.
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!