When mapping smaller arrays to a bigger array, how do I have overlapping elements be added?

9 ビュー (過去 30 日間)
So I am working with stiffness matrices and I am trying to make a global stiffness matrix. I am trying to map each stiffness matrix into a portion of the global stiffness matrix, and wherever the individual matrices overlap, I need the elements to be added. To explain better:
Say I have 2 4x4 matrices:
A = [1 1 1 1;
1 1 1 1;
1 1 1 1;
1 1 1 1]
B = [1 1 1 1;
1 1 1 1;
1 1 1 1;
1 1 1 1]
and I want to map it to one larger 6x6 matrix:
C = [1 1 1 1 0 0;
1 1 1 1 0 0;
1 1 2 2 1 1;
1 1 2 2 1 1;
0 0 1 1 1 1;
0 0 1 1 1 1]
where A and B overlap at C(3:4,3:4), and everywhere that A and B are not is filled up with 0s.
I know that I can map A and B to C by writing:
C(1:4,1:4) = A
C(3:6,3:6) = B
but how do I get C(3:4,3:4) to automatically add the corresponding elements in A and B?

採用された回答

Stephen23
Stephen23 2023 年 2 月 17 日
A = ones(4,4);
B = ones(4,4);
C = blkdiag(A,0,0)+blkdiag(0,0,B)
C = 6×6
1 1 1 1 0 0 1 1 1 1 0 0 1 1 2 2 1 1 1 1 2 2 1 1 0 0 1 1 1 1 0 0 1 1 1 1

その他の回答 (1 件)

Sachin
Sachin 2023 年 2 月 17 日
編集済み: Sachin 2023 年 2 月 17 日
Referring the following information might be of good help to you.
C = zeros(6,6);
A = [1 1 1 1;
1 1 1 1;
1 1 1 1;
1 1 1 1];
B = [1 1 1 1;
1 1 1 1;
1 1 1 1;
1 1 1 1];
C(1:length(A),1:length(A)) = A;
rowidx = 6-length(A)+1; % row index where overlapping starts
colidx = 6-length(A)+1; % col index where overlapping starts
C(rowidx:6,colidx:6) = C(rowidx:6,colidx:6) + B;
C
C = 6×6
1 1 1 1 0 0 1 1 1 1 0 0 1 1 2 2 1 1 1 1 2 2 1 1 0 0 1 1 1 1 0 0 1 1 1 1
This solution can be used for any size square matrix.
Regards
Sachin

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by