Can someone help me understand how this loop works?

n=4;
A = ones(n);
for i= 1:n
for j= 1:n
if (i>2) && (j>2)
A(i,j) = A(i-1,j) + A(i,j-1);
elseif (i<3) && (j<3)
A(i,j) = A(i+1,j) + A(i,j+1);
end
end
end
A

 Accepted Answer

You can add
fprintf('(i=%d, j=%d):', i, j)
disp(A)
pause
after the if in the inner loop and see what happens:
If i and j are both < 3, i.e., in the upper left 2x2 sub-matrix, the values are set to the sum of the value below (A(i+1,j)) and to the right (A(i,j+1)) of i,j. Because the elements in A are initially all 1, the values below and to the right are those initial 1's, so each element in the upper right 2x2 submatrix is set to 1+1 = 2.
If i and j are both > 2, i.e., for the lower right 2x2 submatrix, the values are set to the sum of the value to the left and above i,j. For the first changed values at i=3, j=3, those values are both 1, so this value is set to 2. For the next value to the right, i=3, j=3, the value to the left is not 1, but the just changed value 2, so the sum of the values to the left and above is 2+1 = 3. In the final row, for j = 4, and i = 3, the upper value is the changed value 2, so the value is set to 1+2 = 3. Finally, for j=4, i=4, you have to consider the two 3's from the previous settings, so A(4,4) becomes 3+3.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 23 Nov 2015

Edited:

on 23 Nov 2015

Community Treasure Hunt

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

Start Hunting!