フィルターのクリア

assemble matrices for any matrix size with error of matrix dimension must agree

1 回表示 (過去 30 日間)
Hi all,
I am trying to assmeble matrices, I already wrote a code for which I could do, but I would like to do edit/develop commands so it work for any matrix size.
Now my matrix is 2*2 if i change it to 4*4, or 5*5 and so on.. I get matrix dimension must agree ?
Looking for any help!
clearvars
clc;
NE=2;
NN=NE+1;
NDOF=NN*2
ke=[1 -1;-1 1]; % IF I change this matrix to be 4*4 or 5*5 and so on... will not work to assemble
ke=[1 -1 3;-1 1 5];
K=zeros(NDOF);
for i=1:NE
K(i:i+1,i:i+1)=K(i:i+1,i:i+1)+ke
end

採用された回答

Walter Roberson
Walter Roberson 2021 年 1 月 31 日
編集済み: Walter Roberson 2021 年 1 月 31 日
Why would it assemble? i:i+1 is a vector of length 2. You use it for both indices of K, so K(i:i+1,i:i+1) is going to talk about a 2 x 2 array. You take that 2 x 2 array extracted from K and you add all of ke to it. If ke is not a compatible size to the 2 x 2 array you extracted, then the addition is going to fail.
The compatible sizes of array that can be added to a 2 x 2 array are:
  • 1 x 2 x anything
  • 2 x 1 x anything
  • 2 x 2 x anything
If you want to add all of ke to something extracted from K, then you need the extracted size to be compatible with the size of ke. For example,
NE=2;
NN=NE+1;
NDOF=NN*2
NDOF = 6
ke=[1 -1 3;-1 1 5];
[r, c, ~] = size(ke);
K=zeros(NDOF);
for i=1:NE
K(i:i+r-1,i:i+c-1)=K(i:i+r-1,i:i+c-1)+ke;
end
K
K = 6×6
1 -1 3 0 0 0 -1 2 4 3 0 0 0 -1 1 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  2 件のコメント
Stephen23
Stephen23 2021 年 1 月 31 日
You missed one, Walter Roberson, but it is quite obscure:
  • 1 x 1 x anything
Walter Roberson
Walter Roberson 2021 年 1 月 31 日
True, 1 x 1 x anything would work.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by