我编写了一个matlab代码,希望在找到矩阵中的第一个代码后终止代码。但是,它一直持续到最后一个然后中断。问题是什么?
% The code is as follows:
for i=1:n
for j=1:m
if (bw(i,j)==1) % element with value one
p1(1)=i;p1(2)=j;
% fprintf('value of a: %d\n', i ,j)
sprintf('Found first one in the loop!!')
break; % terminate
end
end
end
答案 0 :(得分:3)
您希望在矩阵中找到第一个1
值,搜索行主要顺序(首先增加列索引,然后行指数)。您可以使用find
函数在没有循环的情况下执行此操作:
M = [0 1; 1 1]; %// example matrix
v = 1; %// value you want to find
[col, row] = find(M.'==v, 1);
请注意,矩阵是转置的,并且find
的两个输出的顺序相反。这是因为Matlab按列主要顺序查找元素(首先增加行索引,然后增加列索引)。
在上面的示例中,使用
M =
0 1
1 1
结果是
row =
1
col =
2
答案 1 :(得分:2)
由于break
仅退出内部循环(使用j
运行的循环)而不退出外部循环(使用i
运行的循环),因此可以通过以下方式解决问题:使用最初设置为false
的简单布尔值
当你打破内部循环时,将其更改为true
,然后检查(在外部循环中)这样的布尔值是否为true
。如果是,也打破外循环。
IWantToBreak=false;
for i=1:n
for j=1:m
if (bw(i,j)==1) % element with value one
p1(1)=i;p1(2)=j;
% fprintf('value of a: %d\n', i ,j)
sprintf('Found first one in the loop!!')
IWantToBreak=true;
break; % terminate
end
end
if IWantToBreak==true
break;
end
end