M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

Index of minimum, excluding negative values

I want to find the index of min element in array L, but negative numbers should be ignored. Is there a simpler way than this?

L = xB./a_i;
for j = 1:length(L)
    if L(j) < 0
        L(j) = Inf;
    end
end
[~, indOut] = min(L);

Upvotes: 1

Views: 576

Answers (2)

Wolfie
Wolfie

Reputation: 30047

Edit:

You can do this in a fairly simple one liner using the same logic

[~, indOut] = min( abs(L)./(L>=0) );

The logic here:

abs(L) % Positive (absolute) values of L
./     % Element-wise divide. Note that x/0 = Inf for x>0
L>=0   % Logical array; 0 when L<0 

% So: Elements where L<0 are divided by 0, and become Inf. 
%     Positive value is the one being divided, so never -Inf

%     Elements where L>=0 are divided by 1, remain unchanged
%     These elements are already positive, so abs(L) == L here.

Either way, you don't need the loop

L( L < 0 ) = Inf;
[~, indOut] = min( L );

Note that, if you didn't want the index (but just the minimum value), you could do this

m = min( L( L >= 0 ) );

Upvotes: 3

Cris Luengo
Cris Luengo

Reputation: 60444

An alternative solution, in case you don’t want to modify L, is to first find the minimum value, and then find its index in a second step:

minL = min(L(L>=0));
index = find(L==minL,1);

Normally it is bad to use equality comparisons with floating-point numbers, but in this case minL must be exactly identical to at least one element in L, so the comparison cannot fail.

Upvotes: 2

Related Questions