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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by