我有这个矩阵:
a = [1 2 2 1; 1 1 2 2]
% 1 2 2 1
% 1 1 2 2
Run Code Online (Sandbox Code Playgroud)
我想找到所有的1并将它们归零.
[~, a_i] = find(a == 1);
a(a_i) = 0
% 0 2 2 1
% 0 0 2 2
Run Code Online (Sandbox Code Playgroud)
为什么第一排还有1?
你正在这样做的方式,你只获得了1 s 的列索引,因为你只使用了第二个输出find.
[~, col] = find(a == 1)
% 1 1 2 4
Run Code Online (Sandbox Code Playgroud)
当你走进以此为指标a它将会把这些作为线性指标,只改变第一,第二和第四个值a成0.线性索引以列主顺序执行,因此这会导致您看到的输出.
要执行您要执行的操作,您需要两个输出find来获取行索引和列索引,然后使用sub2ind它们将这些索引转换为线性索引,然后您可以使用它来索引a.
[row, col] = find(a == 1);
a(sub2ind(size(a), row, col)) = 0;
Run Code Online (Sandbox Code Playgroud)
使用单输出版本find直接返回线性索引并使用它更容易.
ind = find(a == 1);
a(ind) = 0;
Run Code Online (Sandbox Code Playgroud)
或者更好的是,只需使用逻辑索引
a(a == 1) = 0;
Run Code Online (Sandbox Code Playgroud)