Adding Matrices Diagonally for FEM

1 次查看(过去 30 天)
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
  3 个评论
jannat alsaidi
jannat alsaidi 2019-11-10
You can do this,
R=zeros(12,12) W=[1 - 1;-1 1] R(1:2,1:2)=W R(3:4,3:4)=W ... For more help give me the two matrices
Chris Dan
Chris Dan 2019-11-10
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
jannat alsaidi 2019-11-12
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

更多回答(1 个)

jannat alsaidi
jannat alsaidi 2019-11-10
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.
  3 个评论
jannat alsaidi
jannat alsaidi 2019-11-11
yes, it work for different matrices, try it,
A(:,:,1) = [1 -1 1;-1 2 -1; 1 -1 1];
A(:,:,2) = [2 -1 3; -2 5 -6; 7 8 9];
A(:,:,3) = [-8 2 4; -7 9 5; 2 -5 8];
R=zeros(5,5)
for n=1:3
i=n+[0 1 2]
j=i
R(i,j)=R(i,j)+A(:,:,n)
end
R
if there is a different size of (A) matrix change the vector [0 1 2] to the size that is needed, like size(A)= 6×6 the vector will be [0 1 2 3 4 5].
Chris Dan
Chris Dan 2019-11-11
编辑:Chris Dan 2019-11-11
Hey, I ran ur code.
The answer is not correct
can you please check it
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...

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by