简体   繁体   English

查找最小正值及其在矩阵各列中的位置

[英]Finding minimum positive value and its position in each column of a matrix

I need to find the minimum positive values in each column and its position inside the column of a certain matrix. 我需要找到每列的最小正值及其在某个矩阵的列内的位置。 So if I have: 所以,如果我有:

A = [1 4
     2 3
     3 6]

I need to obtain the values 1 and 3, and the positions 1 and 2. Doing this inside a for loop I obtain correctly the minimum values and its position, but it also catches the negative values: 我需要获取值1和3以及位置1和2。在for循环中执行此操作,可以正确获取最小值及其位置,但它还会捕获负值:

for bit = 1:2
    [y(bit),x(bit)] = min(A(:,bit));
end

And if I use: 如果我使用:

[y(bit),x(bit)] = min(A(A(:,bit)>0));

I don't receive the expected result. 我没有收到预期的结果。 What I'm doing wrong? 我做错了什么? Thanks. 谢谢。

This can be easily achieved using inf and min ... 使用infmin可以轻松实现这一点。


New method using inf and no looping 使用inf且无循环的新方法

Take some random example: 举一个随机的例子:

% Generated using A = randi([-100, 100], 10, 3)
A = [ 31    41   -12
     -93   -94   -24
      70   -45    53
      87   -91    59
      36   -81   -63
      52    65    -2
      49    39   -11
     -22   -37    29
      31    90    42
     -66   -94    51];

Set all negative values to positive infinity, which will ensure they are never the minimum value in the column. 将所有负值设置为无穷大,这将确保它们永远不会是列中的最小值。

A(A<=0) = inf; 
% if you want to preserve A, use A2=A; A2(A<=0)=inf;

Now you can just use the min function as expected. 现在,您可以按预期使用min函数。

[mins, idx] = min(A);
% mins = 31, 39, 29: as expected
% idx  = 1, 7, 8: the indices of the above values in each column as expected.

By default, min will get the column-wise minimum as you want. 默认情况下, min将根据需要获得按列的最小值。
To specify this explicitly, use min(A,[],1) , see the documentation for more details. 要明确指定,请使用min(A,[],1) ,有关详细信息,请参阅文档

Note that you could achieve the same result by using NaN instead of inf . 注意 ,使用NaN代替inf可以达到相同的结果。


Your method 你的方法

In response to why you were getting an unexpected result, it's because you weren't selecting the column of A in your loop, the second attempt should be corrected to 针对您为什么得到意外结果的原因,这是因为您没有在循环中选择A的列,因此第二次尝试应更正为

[y(bit),x(bit)] = min(A(A(:,bit)>0, bit));

However , this will still give an unexpected result! 但是 ,这仍然会带来意想不到的结果! The minimums will be correct, but their indices will be lower than expected. 最小值将是正确的,但其索引将低于预期。 This is because the indices will only count the positive values in each column, so you will get the nth positive number rather than the nth number. 这是因为索引将仅计算每列中的正值,因此您将获得第n个数,而不是第n个数。 The easiest "workaround" is to abandon this method and use the quicker one above which doesn't require looping. 最简单的“解决方法”是放弃此方法,并使用上面不需要循环的更快方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM