简体   繁体   English

用条件求矩阵的最小数组

[英]Finding minimum array of matrix with condition

I want to find the minimum of a matrix say A . 我想找到矩阵A的最小值。 I could do it in this way: 我可以这样来做:

NM = find(A==min(A));

but I need the minimum array of A which for it, c(NM) is not zero. 但我需要A的最小数组,为此, c(NM)不为零。 How can I put this condition on finding minimum value? 我如何将这种条件放在寻找最小值上?

Example: 例:

c=[0,18,9,0,100,0]; 
A=[1,189,125,25,7,1];

I expext it returns 5. 我expexp它返回5。

You can use logical indexing to find the desired elements. 您可以使用逻辑索引 找到所需的元素。

find(A==min(A(c~=0)))

Explanation: 说明:

Using logical indexing you first find indices of elements of c that are nonzero. 使用逻辑索引,您首先要找到非零的c元素的索引。

idx1 = c~=0;

then elements of A that correspond to indices of nonzeros elemets of c are extracted. 然后元素A对应的非零元素elemets的索引c被提取。

A1 = A(idx1);

then we find minimum of the extracted elements: 那么我们找到最少的提取元素:

mn = min(A1);

again we use logical indexing to find elements of A that are equal to its minimum. 再次,我们使用逻辑索引查找等于A最小值的元素。

idx2 = A == mn;

finally using find the logical index idx2 converted to linear index. 最后使用find逻辑索引idx2转换为线性索引。

result = find (idx2);

First convert your Matrix to a vector (otherwise the minimum of a Matrix is confusing, it might mean the minimum of each column). 首先将您的Matrix转换为向量(否则Matrix的最小值令人困惑,这可能意味着每列的最小值)。

Then you can sort the Vector and get the indexes 然后您可以对Vector进行排序并获取索引

[val idx] = sort(A(:));

You can then use the indexes to sort your vector c 然后,您可以使用索引对向量c进行排序

c = c(idx);

And finally get the first non-zero element of c: 最后得到c的第一个非零元素:

c = c(c~=0);    
result = c(1);

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

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