How do I alter a row of numbers based on when the number changes?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Olivia Lynes
el 9 de Mzo. de 2016
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 comentarios
MHN
el 10 de Mzo. de 2016
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.
Respuesta aceptada
Ced
el 10 de Mzo. de 2016
Editada: Ced
el 10 de Mzo. de 2016
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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Graphics Object Programming en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!