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 次查看(过去 30 天)
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

采纳的回答

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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by