beesleep , 2 ( ) , 1 ( ). , find
, , .
In fact, to get the index of the second minimum, it is equal to ca. 10 times faster to set the first minimum value inf
(as suggested in the question), and then get the index of the second minimum from the function min
(as opposed to using find
)
[firstMin, firstMinIndex] = min(A(:));
A(firstMinIndex) = inf;
[secondMin, secondMinIndex] = min(A(:));
Here is the code I used to compare this implementation with the one suggested by beesleep :
for i = 1:10
A = rand(10000);
tic
[firstMin, firstMinIndex] = min(A(:));
secondMin = min(A(A~=firstMin));
secondMinIndex = find(A==secondMin); % slow, but use only if you need the index
t1(i) = toc;
tic
[firstMin, firstMinIndex] = min(A(:));
A(firstMinIndex) = inf;
[secondMin, secondMinIndex] = min(A(:));
t2(i) = toc;
end
disp(mean(t1) / mean(t2))
source
share