For loop error, not getting desired output

2 vues (au cours des 30 derniers jours)
Tony Stark
Tony Stark le 12 Sep 2022
Modifié(e) : Chris le 12 Sep 2022
I am having trouble finding the issue with my code. I've tried everything and I still cannot diagnose why this is happening.
When I run this code, I get the answer for all_correct to be the following: all_correct = [0;0;4;]
I know this is wrong, the correct answer should be: all_correct = [4;4;4;]
This is because all x elements are exactly the same to all y elements. I'm not too sure what is wrong with my code, in order to achieve my desired output.
I've tried playing around with the indexes, but it doesn't make a difference.
x = [1 2 3 5; 4 3 1 3; 1 3 3 4];
y = [1 2 3 5; 4 3 1 3; 1 3 3 4];
columns = 3;
for i = 1:columns
correct = 0;
for j = 1:4
if x(i,j) == y(i,j)
correct = correct + 1;
end
all_correct(columns,1) = correct;
end
end

Réponse acceptée

Chris
Chris le 12 Sep 2022
Modifié(e) : Chris le 12 Sep 2022
At the end of the inner for loop, you set
all_correct(columns,1) = correct;
Columns == 3 forever, and correct == 4 by that point. So what you are saying is
all_correct(3,1) = 4;
On the other hand, i iterates in each outer loop.
all_correct(i,1) = correct;
Note this is summing rows, not columns.
Alternatively, you could do:
x = [1 2 3 5; 4 3 1 3; 1 3 3 4];
y = [1 2 3 5; 4 3 1 3; 1 3 3 4];
correct = x==y
correct = 3×4 logical array
1 1 1 1 1 1 1 1 1 1 1 1
all_correct = sum(correct,2)
all_correct = 3×1
4 4 4
This is not only more efficient code-wise, but speed-wise (which doesn't make a difference now, but could with larger arrays). Matlab is not all that good at loops.

Plus de réponses (1)

David Hill
David Hill le 12 Sep 2022
x = [1 2 3 5; 4 3 1 3; 1 3 3 4];
y = [1 2 3 5; 4 3 1 3; 1 3 3 4];
columns = 3;
for i = 1:columns
correct = 0;
for j = 1:4
if x(i,j) == y(i,j)
correct = correct + 1;
end
all_correct(i,1) = correct;%need to index with i
end
end
all_correct
all_correct = 3×1
4 4 4

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