efficient loop - finding min and max index of certain value

2 visualizaciones (últimos 30 días)
mtango
mtango el 9 de Nov. de 2020
Editada: Stephen23 el 9 de Nov. de 2020
I have an array that has for example the following structure:
ic = [ 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3 3 ....... 60000 60000 60000]'
and i want to find the minimum and maximum index of every value in ic. I created the following loop, but it is rather slow:
min_idx = zeros(1, max(ic))';
max_idx = zeros(1, max(ic))';
for n=1:max(ic);
id = ic;
id == n;
idx = find(id);
min_id = min(idx); %should return the minimum index of every value in ic
max_id = max(idx); %should return the miximum index of every value in ic
min_idx(n) = min_id;
max_idx(n) = max_id;
end
With this code it takes around 320 sec to finish. How can this be made faster to run?

Respuesta aceptada

Stephen23
Stephen23 el 9 de Nov. de 2020
Editada: Stephen23 el 9 de Nov. de 2020
Assuming that each value occurs only within one contiguous block:
ic = [1;1;1;1;1;1;1;1;2;2;2;2;2;2;2;3;3;3;3;3;60000;60000;60000];
tmp = diff(ic(:))~=0;
idx_min = find([true;tmp])
idx_min = 4×1
1 9 16 21
idx_max = find([tmp;true])
idx_max = 4×1
8 15 20 23

Más respuestas (1)

David Hill
David Hill el 9 de Nov. de 2020
m=find(diff(ic));
max_idx=[m,length(ic)];
min_idx=[1,m];

Categorías

Más información sobre Loops and Conditional Statements 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!

Translated by