[英]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 例如:
[1, 2, 3, 4]
将不返回任何索引
and [1, 4, -7, -2]
would return 3
并且
[1, 4, -7, -2]
将返回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. 我认为使用
find()
命令一定很简单,但我无法弄清楚如何在这种特定情况下使用它。
Suppose the input matrix is A
, this should do the trick: 假设输入矩阵是
A
,这应该可以解决问题:
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
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
. 在这种情况下,我希望避免
find
调用要快得多。
function [i] = most_negative_index(x)
[mn, i] = min(x);
if mn >= 0
i = [];
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.