MATLAB: How to alter a row of numbers based on when the number changes

consecutive numberslistvalue

I have an array of approximately 80 000 numbers, and I'd like to know how many consecutive numbers of each type there are, and if that number is less than 10000 make those values the same as the previous integer.
For example on a smaller scale when any integer appeared less than 5 times it became the same as the previous value:
8 8 8 8 8 7 7 7 7 7 6 6 6
Would become
8 8 8 8 8 7 7 7 7 7 7 7 7
both 8 and 7 appear 5 times in the original list so would remain unchanged, but 6 only appears 3 times so it becomes 7 for all 3 values.
Many thanks

Best Answer

Maybe something like this? Not pretty, but not fully brute force either. Since you are looking at fairly big chunks (1000), this should be quite fast.
For any order:
a = [8 8 8 8 8 7 7 7 7 7 6 6 6 3 3 3 1 1 1 0 0 0 0 0];
N = 5;
M = length(a);
ind = 1;
while ( ind <= M )
% are the next N numbers the same?
if ( all( a(ind) == a(ind:min(M,ind+N-1)) ) ) % if yes, skip ahead
ind = ind + N;
while ( ind <= M && a(ind) == a(1) ) % while the next one is the same
ind = ind + 1;
end
else % if no, set all numbers the same, skip ahead
a(ind:min(M,ind+N-1)) = a(max(1,ind-1));
ind = ind + N-1;
end
end
Note that these weird min/max expressions are only there to make sure I don't run over the boundaries (I hope I didn't miss anything).
Now if they are sorted, I'm sure you can find tricks to avoid (almost) any loops. E.g if you want to count the occurrences and see which ones you have to replace:
a = [8 8 8 8 8 7 7 7 7 7 6 6 6 3 3 3 1 1 1 0 0 0 0 0];
M = length(a);
N = 5;
% get indices of changing numbers
[ unique_num, index, rev_index ] = unique(a,'stable');
% See how many are consecutive by looking at difference
% calculate last one with distance from end
N_occurrence = [ diff(index) ; length(a)-index(end) + 1 ];
% These numbers need to be fixed:
fix_numbers = (N_occurrence < N);
% now fix numbers, etc.
Good luck!