MATLAB: Adding Matrices Diagonally for FEM

diagnoal additionfor loopmatrices

Hello.
I am trying to make a diagnoal matrix in which the three matrices overlap.
I am attaching a picture which will make things more clear.
I can do it for 2×2, but for 3×3 or more like 12×12. I am having confusion.
Can somebody help me expand the logic of 2×2, that would be very nice
here is the code:
B = [ 1 -1;
-1 1];
C = [ 1 -1;
-1 1];
D = [ 1 -1;
-1 1];
T = zeros(4,4)
d=zeros(2,2,3);
d(:,:,1) = B;
d(:,:,2) = C;
d(:,:,3) = D;
for k = 1:1:3
for i = 1:1:2
for j = 1:1:2
T(i+k-1,j+k-1) = T(i+k-1,j+k-1) + d(i,j,k);
end
end
end

Best Answer

A(:,:,1) = [1 -1 1;-1 2 -1; 1 -1 1];
A(:,:,3) = [1 -1 1;-1 2 -1; 1 -1 1];
A(:,:,5) = [1 -1 1;-1 2 -1; 1 -1 1];
R=zeros(7,7)
for n=1:2:5
i=n+[0 1 2]
j=i
R(i,j)=R(i,j)+A(:,:,n)
end