How to add values to already existing ones in a matrix using for loop?
3 ビュー (過去 30 日間)
古いコメントを表示
Hi, my function looks like this:
nEN=[1 2 4 5];
KG=[];
for i1=1:4
KG((2*(nEN(i1))-1),(2*(nEN(i1))-1))=Ke((2*i1-1),(2*i1-1));
KG(2*(nEN(i1)),2*(nEN(i1)))=Ke((2*i1),(2*i1));
end
Basically it assigns values from matrix 'Ke' (8x8 with constants) to matrix 'KG' which is initially filled with zeros. Numbers of rows and columns are given by the array nEN, which varies in another loop which is not shown here. The thing is sometimes nEN can have the same values as those obtained in the previous iteration, and so my loop rewrites the values which have been already present in 'KG', but I want them to be added together instead. How can I do that?? Thanks.
0 件のコメント
採用された回答
その他の回答 (1 件)
Cedric
2013 年 4 月 21 日
編集済み: Cedric
2013 年 4 月 21 日
Like this:
KG = zeros(size(Ke)) ; % Prealloc (are they same size?)
% and initialize with 0's.
for ...
nEN = [1 2 4 5] ; % Defined in the external loop.
for i1 = 1 : 4
bi_KG = 2 * nEN(i1) ; % Base index for KG.
bi_Ke = 2 * i1 ; % Base index for Ke.
KG(bi_KG-1,bi_KG-1) = KG(bi_KG-1,bi_KG-1) + Ke(bi_Ke-1,bi_Ke-1) ;
KG(bi_KG,bi_KG) = KG(bi_KG,bi_KG) + Ke(bi_Ke,bi_Ke);
end
end
2 件のコメント
Cedric
2013 年 4 月 21 日
You're welcome; note that I edited my answer a minute after posting it because I had made a mistake by copy/paste-ing a little to fast.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!