我有一个[m,n]
矩阵,我希望找到不是0
的值的位置并在屏幕上打印它们。使用循环我做:
disp('4) go through C and print (i,j) where element is not 0');
[m,n] = size(C);
for i= 1:m
for j= 1:n
if(C(i,j) ~= 0)
result = sprintf('Element at [%d,%d] is not 0, is %d', ...
i, j, C(i,j));
disp(result);
end
end
end
输出是这样的:
Element at [1,1] is not 0, is 1
Element at [1,2] is not 0, is 1
Element at [1,3] is not 0, is 1
Element at [1,4] is not 0, is 1
如何使用find
命令执行完全相同的操作?我尝试了下面的代码,但它产生了3个一维数组......如何关联和提取它们的输出?或者我做错了什么?
%Do the same thing with find
[i,j,k] = find(C ~= 0)
答案 0 :(得分:4)
find
函数的输出参数组织如下:
[Row of element, Column of element, Value of element]
因此,使用此命令:
[r,c,v] = find(C)
将产生3个Nx1阵列,每个阵列包含上述信息。
因此,您可以使用以下代码来实现所需,使用循环索引访问数组中的每个值。请注意,您可以使用fprintf打印带格式的文本,而不是同时使用sprintf
和disp
。
[r,c,v] = find(C);
for k = 1:size(r,1)
fprintf('Element at [%d,%d] is not 0, it is %d\n',r(k),c(k),v(k));
end
使用此输入矩阵:
C = [1 0 0 1;0 1 0 1;0 0 1 1]
C =
1 0 0 1
0 1 0 1
0 0 1 1
我们获得以下输出:
Element at [1,1] is not 0, is 1
Element at [2,2] is not 0, is 1
Element at [3,3] is not 0, is 1
Element at [1,4] is not 0, is 1
Element at [2,4] is not 0, is 1
Element at [3,4] is not 0, is 1