首页 > 解决方案 > 在MATLAB中查找一行中唯一零的列号

问题描述

我有一个仅由 1 和 0 组成的大矩阵。在仅包含一个零的行中,我需要找到该零的索引(或零的列号)。

我正在尝试使用以下命令,但它只返回相关行的行号。谁能告诉我如何修改这个命令或添加一个额外的命令来找到那个零的列号?

find(sum(~A,2) == 1)

标签: matlab

解决方案


您的问题是这sum(~A,2) == 1是一个列向量,因此您会丢失有关所需列的数据。

您可以执行以下操作:

% (A == 0)         : Elements where A is zero
% (sum(~A,2) == 1) : Rows where there's exactly 1 zero
% We want the matrix where both of these are true...
idx = (sum(~A,2) == 1) .* (A == 0);  
% We want the row and column indices of the zeros
[r,c] = find( idx );

例子:

% A with single-zero rows in positions (2,1) and (4,2)
A = [ 1 1 1 1 1 1
      0 1 1 1 1 1
      1 0 1 0 1 1 
      1 0 1 1 1 1 
      1 1 1 1 1 1 
      1 1 1 1 0 0 ];

idx = (sum(~A,2) == 1) .* (A == 0); % Could replace (A==0) with (~A)
[r,c] = find(idx)

% r = [2; 4]
% c = [1; 2]; 

注意:这取决于隐式扩展,与 MALTAB R2016b 或更高版本兼容。您没有在问题中提及您的版本,但对于旧版本,请使用idx

idx = bsxfun( @times, (sum(~A,2) == 1), (A == 0) );

推荐阅读