For loop error, not getting desired output

1 次查看(过去 30 天)
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