在MATLAB中找到行中唯一零的列号

时间:2019-03-19 10:15:56

标签: matlab

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

我正在尝试使用以下命令,但它仅返回有关行的行号。谁能告诉我如何修改此命令或添加其他命令以查找该零的列号?

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

3 个答案:

答案 0 :(得分:3)

您的问题是marian-decoder是列向量,因此您会丢失有关所需列的数据。

您可以执行以下操作:

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 );

注意:这取决于隐式扩展,与MALTAB R2016b或更高版本兼容。您没有在问题中提及您的版本,但是对于较旧的版本,请在% 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]; 中使用它:

idx

答案 1 :(得分:3)

您可以使用min查找每行最小元素的索引,然后使用行号提取列索引:

[~, idx] = min(A, [], 2);
r = find(sum(~A, 2) == 1);
c = idx(r);

使用以下方法可能会更有效:

r = find(sum(A, 2) == size(A,2)-1);

答案 2 :(得分:1)

您可以在下一个方向再次运行命令。如果您有未定义的行数,那么循环执行将很方便:

rows = find(sum(~A,2) == 1);
columns=[];
for i = 1:length(rows)
    columns(end+1)=find(sum(~A(rows(i),:),1)==1);
end
disp(rows)
disp(columns)