matlab - 在MATLAB中查找一行中唯一零的列号
问题描述
我有一个仅由 1 和 0 组成的大矩阵。在仅包含一个零的行中,我需要找到该零的索引(或零的列号)。
我正在尝试使用以下命令,但它只返回相关行的行号。谁能告诉我如何修改这个命令或添加一个额外的命令来找到那个零的列号?
find(sum(~A,2) == 1)
解决方案
您的问题是这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) );
推荐阅读
- c++ - 我可以在 C++ 中输出数组的内存地址吗?
- python - 要知道递归背包问题python中拿了什么物品
- powerbi - 出于效率目的使用变量的 DAX 函数
- javascript - 使用 foreach 向项目添加新属性不起作用
- node.js - 在 mongodb 中更新和插入多个文档
- swift - 将 CorePlot 添加到迦太基后构建失败错误
- mysql - 错误代码:1210. MySQL Workbench 中视图上的 MATCH 参数不正确
- hashicorp-vault - 检查密封状态时出错:获取 https://127.0.0.1:8200/v1/sys/seal-status: x509:
- amazon-web-services - 来自后端资源的 Websocket 事件?
- powerbi - PowerBI:计算表包含一个值而不是另一个值