MATLAB: How does the operation take place for, b (2:6, 2:6) = b(1:5, 2:6) + b(3:7, 2:6) + b(2:6, 1:5) + b(2:6, 3:7); , row-wise manner

loop inside arraymatrix looping

Can you please explain the functional difference between the following 2 cases. I want to understand how case 1 works actually.
a is matrix of dimension 7×7 or higher.
Intended Operation: Each interior pixel is sum of its 4 non-diagonal neighbors
_________________________________________________________________
case 1
b = a;
b (2:6, 2:6) = b(1:5, 2:6) + b(3:7, 2:6) + b(2:6, 1:5) + b(2:6, 3:7);
case 2
b = a;
for i=2:6
for j=2:6
b (i, j) = b(i-1, j) + b(i+1, j) + b(i, j-1) + b(i, j+1);
end
end

Best Answer

The first code extracts all the various subsets of the b array before doing any assignments. For example b(3,4) is part of each of those operands, and it is the same b(3,4) that is fetched for each one (in the appropriate position in its sub array) and no changes to b are made until after all of the additions are done.
The second code changes b as it goes, so after the first round of changes, b(i-1,j) refers to the already changed location, not to what was originally there.
You can avoid the problem by changing all the b references on the right hand side of the assignment into a references
b(i,j) = a(i-1,j) + a(i+1, j) + a(i, j-1) + a(i,j+1);