# Adding Matrices Diagonally for FEM

5 views (last 30 days)
Chris Dan on 10 Nov 2019
Answered: jannat alsaidi on 12 Nov 2019
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 2x2, but for 3x3 or more like 12x12. I am having confusion.
Can somebody help me expand the logic of 2x2, 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
Chris Dan on 10 Nov 2019
The two matrices are
A == [ 1 -1 1;-1 2 -1; 1 -1 1]
B == [ 1 -1 1;-1 2 -1; 1 -1 1]

jannat alsaidi on 12 Nov 2019
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

jannat alsaidi on 10 Nov 2019
A = [ 1 -1 1;-1 2 -1; 1 -1 1];
%A=B
R=zeros(6,6)
for n=1:3
i=n+[0 1 2]
j=i
R(i,j)=R(i,j)+A
end
R
You can change vector [1 2 3], to choose the elements that you need to add them.
Chris Dan on 11 Nov 2019
Edited: Chris Dan on 11 Nov 2019
Hey, I ran ur code.
The answer which I should get for
A(:,:,1) = [1 -1 1;-1 2 -1; 1 -1 1];
A(:,:,2) = [1 -1 1;-1 2 -1; 1 -1 1];
A(:,:,3) = [1 -1 1;-1 2 -1; 1 -1 1];
R=zeros(6,6)
for n=1:3
i=n+[0 1 2]
j=i
R(i,j)=R(i,j)+A(:,:,n)
end
is
R =[ 1 -1 1 0 0 0 0;
-1 2 -1 0 0 0 0;
-1 -1 2 -1 -1 0 0;
0 0 -1 2 -1 0 0;
0 0 1 -1 2 -1 -1;
0 0 0 0 -1 2 -1;
0 0 0 0 1 -1 1 ]
BUT I am getting :
1 -1 1 0 0 0
-1 3 -2 1 0 0
1 -2 4 -2 1 0
0 1 -2 3 -1 0
0 0 1 -1 1 0
0 0 0 0 0 0
0 0 0 0 0 0
This is wrong...