获取列及其索引的非零最小值

Get the non-zero minimum of a column and its index

我想找到非负整数矩阵的一列的最小值,不包括 0。我知道矩阵是正方形的,并且在其主对角线的每个元素上只有零(即 a(i,i)=0 for all i).

我试过这个:

[best_cost,index] = min(star_costs([1:i-1,i+1:nbr],i));

其中 nbr 是我的矩阵的大小。

然而,返回的索引是不包括零的索引,不考虑第 i 个元素。比如我的第一列是:

[0 9 11 5 18 13 14]'

所以代码 returns best_cost=5index=3 因为 0 元素被排除在外。但是,我想得到 index=4 正如任何人所期望的那样。

当然,只加 1 是没有意义的,因为它可能发生在任何列上,除了第一列的情况外,该列的最小值可能在对角线上方或下方。

正如评论中所建议的那样,我会尝试将对角线更改为矩阵的最大值,假设只省略对角线上的零。

%create random matrix
A = magic(4)
%change diagonal to the maximum
A(logical(eye(size(A)))) = max(A(:));

现在您可以将搜索应用到最小值

inf 替换零,然后使用 min

A(1:size(A,1)+1:end) = inf;    %If the diagonal is to be excluded
%if all zeros are to be excluded including non-diagonal elements, use this instead:
%A(A==0) = inf;                %Use tolerance if you have floating point numbers
[best_cost, index] = min(A);