MATLAB: Given a matrix A, create the matrix B whose elements are the neighbor sumr for A

columnelementelementsfunctionmatlab functionmatrixrowsum

I'm havig trouble on matrix B, I should get B = [7 10 13 11; 16 24 28 23; 28 40 44 35; 23 28 41 27]
but, I'm getting B =
13 13 13 23
16 24 28 20
28 40 44 32
0 38 41 27
A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
C = size(A)
M = C(1)
N = C(2)
% Step 1: Get elements of the first row of matrix B from matrix A:
B(1,1) = A(1,2) + A(2,1)
for j = 2:N-1
B(1:j) = A(1,j-1) + A(2,j) + A(1,j+1)
end
B(1,N) = A(1,N-1) + A(2,N)
% Step 2: Get elements of the middle rows of Matrix B from matrix A:
for i = 2:M-1
B(i,1) = A(i-1,1) + A(i,2) + A(i+1,1)
end
for j = 2:N-1
for i = 2:M-1
B(i,j) = A(i,j-1) + A(i-1,j) + A(i+1,j) + A(i,j+1)
end
end
for i = 2:M-1
B(i,N) = A(i,j-1) + A(i-1,j) + A(i+1,j)
end
% Step 3: Get elements of the last row of matrix B from matrix A:
B(1,N) = A(N-1,1) + A(N,2)
for j = 2:N-1
B(N,j) = A(N,j-1) + A(N-1,j) + A(N,j+1)
end
B(M,N) = A(M,N-1) + A(M-1,N)
disp(B)

Best Answer

There are multiple indexing errors in your code Jose. Here is the rectified version.
A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
C = size(A)
M = C(1)
N = C(2)
% Step 1: Get elements of the first row of matrix B from matrix A:
B(1,1) = A(1,2) + A(2,1)
for j = 2:N-1
B(1,j) = A(1,j-1) + A(2,j) + A(1,j+1)
end
B(1,N) = A(1,N-1) + A(2,N)
% Step 2: Get elements of the middle rows of Matrix B from matrix A:
for i = 2:M-1
B(i,1) = A(i-1,1) + A(i,2) + A(i+1,1)
end
for j = 2:N-1
for i = 2:M-1
B(i,j) = A(i,j-1) + A(i-1,j) + A(i+1,j) + A(i,j+1)
end
end
for i = 2:M-1
B(i,N) = A(i,N-1) + A(i-1,N) + A(i+1,N)
end
% % Step 3: Get elements of the last row of matrix B from matrix A:
B(N,1) = A(N-1,1) + A(N,2)
for j = 2:N-1
B(N,j) = A(N,j-1) + A(N-1,j) + A(N,j+1)
end
B(M,N) = A(M,N-1) + A(M-1,N)
disp(B)