Home > OS >  For loop Error, not outputting my desired output
For loop Error, not outputting my desired output

Time:09-12

Can someone please provide an explanation to me why my code is not working as I am trying to get, and what is the correct way to implement my code?

Here is my code:

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

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.

CodePudding user response:

It is just a typo in your code, it should be all_correct(i,1) = correct; instead of all_correct(columns,1) = correct;.

As columns is always 3, you only assign to the third position in all_correct.

[Edit] Moreover, as noticed and commented by Cris Luengo below your question, you could also move all_correct(i,1) = correct; outside the loop over j.

An improved version of your code would be:

all_correct = sum( x == y, 2 )

Explanation:

  • x == y provides a logical array showing where x and y are equal.
  • sum( x == y, 2 ) the sums up over the rows.
  • Related