I am trying to assemble a matrix in which I would like to put small matrices into a big one but I don't know how to do that,
I know that I have to define the big matrix first and then show put the small ones inside
for example I have k1=[1 -1; -1 1] , K2=[1 -1; -1 1] and the define bigK in which bigK=zeros(3,3) and in the end I want it to be like bigK = [ 1 -1 0; -1 2 -1; 0 -1 1]
in which the small matrices will assemble in diagonal way
how I can do it using a for loop ?

 採用された回答

John D'Errico
John D'Errico 2018 年 10 月 12 日

0 投票

K = zeros(10,10);
k = [1 -1; -1 1];
for n = 1:9;
rind = n + [0 1];
cind = rind;
K(rind, cind) = K(rind, cind) + k;
end
There are better ways to do this in terms of pure efficiency. But the above will suffice. First learn how to write at least decent code that solves the task at hand. Only when you decide if the code is a problem do you want to worry about optimizing it for speed.

5 件のコメント

John D'Errico
John D'Errico 2018 年 10 月 12 日
Please don't add answers just to make a comment. Moved to a comment by the op:
"rind = n + [0 1]; cind = rind; I did not understand why you did this"
John D'Errico
John D'Errico 2018 年 10 月 12 日
Why I did it? rind is the name I chose for RowIndex. cind stood for ColumnIndex.
So think about what the code does as I wrote it, and where in the matrix it puts k.
abdelrahman alhammadi
abdelrahman alhammadi 2018 年 10 月 12 日
but why n+[0 1] ?
abdelrahman alhammadi
abdelrahman alhammadi 2018 年 10 月 12 日
is there another way of doing it in a for loop in which I only define the small k function and size of big k and then it will do it by itself ?
Torsten
Torsten 2018 年 10 月 12 日
k=[1 -1; -1 1];
n=5;
K=zeros(n+1);
for i=1:n
K(i:i+1,i:i+1)=K(i:i+1,i:i+1)+k;
end
K

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

その他の回答 (3 件)

Torsten
Torsten 2018 年 10 月 12 日

3 投票

k1 = [1 -1; -1 1];
k2 = k1;
K = zeros(3,3)
K(1:2,1:2) = k1;
K(2:3,2:3) = K(2:3,2:3) + k2;
K
abdelrahman alhammadi
abdelrahman alhammadi 2018 年 10 月 12 日

0 投票

what if I have vector a1= [1; -1] and a2= [ 1 ;-1 ] and so on ... the big matrix F= [ 1; 0; 1] if the size was(2) how can I do that in a for loop ?

2 件のコメント

John D'Errico
John D'Errico 2018 年 10 月 12 日
Please stop adding multiple answers for every single comment!
Beck Rinks
Beck Rinks 2022 年 7 月 25 日
Please only reply if you are giving answers. Thanks.

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

Samba Dumbuya
Samba Dumbuya 2022 年 12 月 1 日

0 投票

Hello,
I have computed the following stiffness matrix by hand;
[2/3 -1/6 -1/6 -1/3; -1/6 2/3 -1/3 -1/6;-1/6 -1/3 2/3 -1/6; -1/3 -1/6 -1/6 2/3]
Can someone please with codes that assemble the stiffness matrix into global matrix. The domain is discritize to square elemen.
thanks

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by