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

조회 수: 2 (최근 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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by