0
x=[3 1 1 -5 -2 0 1 2 -2 2];
A=[4 2 6; 0 1 -3; -2 5 -2];
B=[-2 3 2; 1 5 5; -3 1 0];

sum=0;
for i=2:3
    sum_j=0;
    for j=1:2
        sum_j=sum_j+A(1,j)*B(j,i);
    end
    sum=sum+A(2,i)*sum_j;
end
fprintf('(c) %g\n',sum);

>> (c) -32

-32 is a correct answer. However, if I initialize sum_j=0 outside of the the loop, it returns a different value.

sum=0;
sum_j=0;
for i=2:3
    for j=1:2
        sum_j=sum_j+A(1,j)*B(j,i);
    end
    sum=sum+A(2,i)*sum_j;
end
fprintf('(c) %g\n',sum);

>> (c) -98

Can anyone explain why this is happening?

1
  • This is obviously what is happening. In the first place you set sum_j to zero for every "i" and in the second place you don't. Commented Mar 5, 2017 at 12:27

1 Answer 1

1

In your first code sum_j gets reinitialized in the loop for i and in second code sum_j carry the value in each loop. Here is a simulation of your codes

first code:

sum = 0
i=2:
    sum_j = 0
i=2,j=1
    sum_j = 0 + 4*3 = 12
i=2,j=2
    sum_j = 12 + 2*5 = 22
  sum = 0 + 1*22 = 22
i=3
    sum_j = 0
i=3,j=1
    sum_j = 0 + 4*2 = 8
i=3,j=2
    sum_j = 8 + 2*5 = 18
  sum = 22 + -3*18 = -32

Second code

sum = 0
sum_j = 0
i=2:
i=2,j=1
    sum_j = 0 + 4*3 = 12
i=2,j=2
    sum_j = 12 + 2*5 = 22
  sum = 0 + 1*22 = 22
i=3
i=3,j=1
    sum_j = 22 + 4*2 = 30
i=3,j=2
    sum_j = 30 + 2*5 = 40
  sum = 22 + -3*40 = -98
Sign up to request clarification or add additional context in comments.

1 Comment

Great!! that perfectly explains

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.