Gradient
Gradient

Reputation: 2343

Matlab, find index of minimum value with the condition that it must be negative

In a given array, I need to find the index of the minimum value in an array, but only if it is negative.

For example : [1, 2, 3, 4] would return no indices

and [1, 4, -7, -2] would return 3

I was thinking that it must be simple with the find() command, but I couldn't figure out how to use it for this specific situation.

Upvotes: 3

Views: 7604

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283624

Sometimes, throwing everything into one complicated vector expression isn't optimal.

In this instance, I expect it to be much faster to avoid a call to find.

function [i] = most_negative_index(x)
   [mn, i] = min(x);
   if mn >= 0
       i = [];
   end
end

Upvotes: 4

Roney Michael
Roney Michael

Reputation: 3994

Suppose the input matrix is A, this should do the trick:

find(A==min(A) & A<0)

For example:

>> A = [1, 2, 3, 4];
>> B = [1, 4, -7, -2];
>> find(A==min(A) & A<0)

ans =

   Empty matrix: 1-by-0

>> find(B==min(B) & B<0)

ans =

     3

Upvotes: 5

Related Questions