For loop error, not getting desired output
3 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Chris
on 12 Sep 2022
Edited: Chris
on 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
all_correct = sum(correct,2)
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.
0 Comments
More Answers (1)
David Hill
on 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
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!