How do I alter a row of numbers based on when the number changes?
1 次查看(过去 30 天)
显示 更早的评论
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
5 个评论
MHN
2016-3-10
Two questions and I will answer your question: 1- what if the first number occurs less than 5 times? 2- Are the numbers consecutive? i.e. if there is [6 6 6 5 5 ...] is there any 6 in ... part? If no, there is an easy way to do what you want.
采纳的回答
Ced
2016-3-10
编辑:Ced
2016-3-10
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!
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!