3

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.

Dan
  • 45,079
  • 17
  • 88
  • 157
Gradient
  • 2,253
  • 6
  • 25
  • 36

2 Answers2

5

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
Roney Michael
  • 3,964
  • 5
  • 30
  • 45
  • 1
    I initially posted a function, then came up with: `find(cell2mat(arrayfun(@(x)eq(x,min(A(sign(A) == -1))),A,'UniformOutput',false)))` . LOL, sometimes you need to take a step back and think about things before you start coding... – JustinBlaber Mar 19 '13 at 04:51
  • @jucestain: Yeah. :D It happens to the best of us at times. – Roney Michael Mar 19 '13 at 04:54
  • It might be worth noting that this is about 3 times slower than the solution posted by Ben Voigt, just something to consider. – Dan Mar 19 '13 at 06:25
  • @Dan Depends on what OP is doing. If his implementation needs the function above once or twice it should be fine. Implementing Ben's solution will require either a separate function file or a function appended to the end of another function file, which will limit the scope of that function anyway. I also just tic toc'd this solution for a 100k vector and it took 0.001 seconds. IMO its much better to go with the clear and concise solution (as above) and worry about optimization later, but ultimately it depends on OP's problem. – JustinBlaber Mar 19 '13 at 06:47
  • @jucestain I was just pointing it out as it's worth considering. But you don't need a separate function at all. It may not be one line but there is no reason why it can't go in the code exactly where this solution does. – Dan Mar 19 '13 at 06:56
  • @Dan You're right... My bad. For some reason this question messing with me :P. – JustinBlaber Mar 19 '13 at 07:02
4

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
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720