Adding Matrices to make Bigger Matrix

Hello
I have a problem related to FEM. I want to add two stiffness matrices. Such as
A = [ 1 -1;
-1 1];
and
B = [ 2 -2;
-2 2];
The result which I should get is
C = [1 -1 0;
-1 3 -2;
0 -2 2];
C is a 3x3 matrix and A is a 2x2 matrix, B is also a 2x2 matrix
Does anybody know how to do it in a loop and how to expand it to more matrices, such as if I have 3 or 4 matrices instead of 2 and I want to add them this way.

 採用された回答

the cyclist
the cyclist 2019 年 11 月 6 日
編集済み: the cyclist 2019 年 11 月 6 日

0 投票

Here is a straightforward way to do it with a for loop:
A{1} = [ 1 -1;
-1 1];
A{2} = [ 2 -2;
-2 2];
A{3} = [ 3 -3;
-3 3];
numberMatrices = size(A,2);
output = zeros(numberMatrices+1);
for na = 1:numberMatrices
output(na:na+1,na:na+1) = output(na:na+1,na:na+1) + A{na};
end
It relies on having stored your input arrays sensibly in a cell array, rather than as variables named A,B,C,..., Z.

4 件のコメント

Chris Dan
Chris Dan 2019 年 11 月 7 日
編集済み: Chris Dan 2019 年 11 月 7 日
Hey,
Thanks for the answer, but I donot understand this line
"It relies on having stored your input arrays sensibly in a cell array, rather than as variables named A,B,C,..., Z."
Also, will this method also work for sparse matrices or bigger matrices like 3x3 or nxn matrices?
Stephen23
Stephen23 2019 年 11 月 7 日
"It relies on having stored your input arrays sensibly in a cell array..."
Because accessing those arrays within a cell array is simple and very efficient using indexing.
"... rather than as variables named A,B,C,..., Z."
What you showed in your question uses different variable names for each matrix. Accessing variable names dynamically is slow, complex, buggy, and hard to debug.
the cyclist
the cyclist 2019 年 11 月 7 日
Yes, what Stephen wrote. Although you can still make my solution work, if you do
B = [ 1 -1;
-1 1];
C = [ 2 -2;
-2 2];
D = [ 3 -3;
-3 3];
A = {B,C,D};
before using my algorithm.
Walter Roberson
Walter Roberson 2019 年 11 月 7 日
For larger matrices you need to define whether the offset to add them at is down by 1 diagonally each time, or the the rule is to overlap just the last entry.

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2019 年 11 月 7 日

0 投票

It is probably easiest to intialize C to zeros() and then loop over a cell array {A, B, third, fourth} adding them into the appropriate section of C cumulatively.
There are other options, but they are not nearly as clear.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by