For loop error, not getting desired output

조회 수: 2 (최근 30일)
Tony Stark
Tony Stark 2022년 9월 12일
편집: Chris 2022년 9월 12일
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

채택된 답변

Chris
Chris 2022년 9월 12일
편집: Chris 2022년 9월 12일
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.

추가 답변 (1개)

David Hill
David Hill 2022년 9월 12일
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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by