How to use break/continue?

11 vues (au cours des 30 derniers jours)
Sherwin
Sherwin le 26 Avr 2022
Hi, I have the following matrices,
AT = [1 1 0 0 0 ; 0 0 1 1 0; 1 0 0 1 1]; % a 3*5 matrix
yHT = [1 ; 1 ; 0 ; 0 ; 1]; % a 5*1 array
I want to use loops to go through these two matrices and for each row of AT, for all elements that are 1, if the respective element on yHT is 1 too, return 1, if not, then return 0 (even if only 1 respective element on yHT is 0 it should return 0); and then repeat this for every row of AT. I tried the following loop but it I think I am using break or continue wrong or maybe my whole code is wrong. Can someone please help me?
for i = 1:3
counter = 0;
for j = 1:5
if AT(i,j) == 1
if yHT(j,1) == 1
counter = 1;
break
else
counter = 0;
continue
end
else
counter = 0;
continue
end
end
end
  3 commentaires
Sherwin
Sherwin le 26 Avr 2022
Is it the same as &&?
Walter Roberson
Walter Roberson le 26 Avr 2022
&& is restricted to scalars.

Connectez-vous pour commenter.

Réponses (1)

Arjun
Arjun le 9 Oct 2024
I see that you want to understand the use of continue/break statement to implement your programming logic.
To implement the logic correctly, you should iterate through each row of the "AT" matrix and check the corresponding elements in the "yHT" vector. If all elements in "yHT" that correspond to the 1s in "AT" are also 1, then return 1 for that row; otherwise, return 0. You do not need to use "continue" at all. Instead, simply use "break" to exit the loop immediately if the condition fails for any element while analysing a row, as there is no need to check the entire row in such cases.
Kindly refer to the code below for better understanding:
% Initialize matrices
AT = [1 1 0 0 0; 0 0 1 1 0; 1 0 0 1 1];
yHT = [1; 1; 0; 0; 1];
result = zeros(size(AT, 1), 1);
for i = 1:size(AT, 1)
allOnesMatch = true;
for j = 1:size(AT, 2)
if AT(i, j) == 1
if yHT(j, 1) ~= 1
% If a corresponding element in yHT is not 1, set flag to false
allOnesMatch = false;
break; % No need to check further, this row fails the condition
end
end
end
if allOnesMatch
result(i) = 1;
else
result(i) = 0;
end
end
disp(result);
Kindly refer to the documentation of “break” and “continue” statements:
I hope this helps!

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by