フィルターのクリア

break from a nested for loop

13 ビュー (過去 30 日間)
kurdistan mohsin
kurdistan mohsin 2022 年 5 月 10 日
コメント済み: kurdistan mohsin 2022 年 5 月 16 日
hi, i have the below matrix , i want each row to have only on value equal to '1' , so when searching if it find a one it will take it and make the rest values of the row equal to zero . i write the bellow code , i need to break the second loop when the if condtion is true , any one can help?
D=[ 1 1 1 1 1
1 1 1 1 1
0 0 0 0 0
0 1 0 0 0
1 1 0 1 1
0 0 1 0 0
0 0 0 0 0
0 0 1 0 0
1 0 0 1 1
0 0 0 0 0]
D = 10×5
1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 0 0 0 1 1 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 1 0 0 0 0 0
N=10;
M=5;
for n=1:N
for m=1:M
if D(n,m)==1
Dn(n,m)=1;
Dn(n,m+1:end)=0;
else Dn(n,m)=0;
end
end
end
Dn
Dn = 10×5
1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 0 0 0 1 1 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 1 1 0 0 0 0 0

採用された回答

Image Analyst
Image Analyst 2022 年 5 月 10 日
Try using a flag
abort = false;
for n = 1 : N
for m = 1 : M
if conditionForBreaking
abort = true; % Set flag
break; % Exit inner loop.
end
end
if abort
break % exit outer loop.
end
end
  3 件のコメント
Image Analyst
Image Analyst 2022 年 5 月 11 日
Why not simply use find instead of all that complicated stuff (abort flag and nested loops):
D=[ 1 1 1 1 1
1 1 1 1 1
0 0 0 0 0
0 1 0 0 0
1 1 0 1 1
0 0 1 0 0
0 0 0 0 0
0 0 1 0 0
1 0 0 1 1
0 0 0 0 0];
[rows, columns] = size(D);
for row = 1 : rows
indexOfFirst1 = find(D(row,:) == 1, 1, 'first');
if ~isempty(indexOfFirst1)
% If there is a one in the row, make all elements
% in the row zero after that one.
D(row, indexOfFirst1+1:end) = 0;
end
end
D
D = 10×5
1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0
kurdistan mohsin
kurdistan mohsin 2022 年 5 月 16 日
it works too, thanks again

サインインしてコメントする。

その他の回答 (1 件)

Mitch Lautigar
Mitch Lautigar 2022 年 5 月 10 日
Using Matlabs "continue" command should do what you need.
  1 件のコメント
kurdistan mohsin
kurdistan mohsin 2022 年 5 月 11 日
thank you

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by