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.

1
  • I discovered it myself when I tried your question. :D Mar 19, 2013 at 4:47

2 Answers 2

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
6
  • 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... Mar 19, 2013 at 4:51
  • @jucestain: Yeah. :D It happens to the best of us at times. Mar 19, 2013 at 4: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, 2013 at 6: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. Mar 19, 2013 at 6: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, 2013 at 6:56
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.