Clear Filters
Clear Filters

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 ?

2 views (last 30 days)
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 7x7 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

Accepted Answer

Walter Roberson
Walter Roberson on 17 Mar 2019
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);

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!