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.

采纳的回答

Vitaly
Vitaly 2013-4-21
Nevermind, I solved the problem by accumulating values in KG with:
KG((2*(nEN(i1))-1),(2*(nEN(i2))-1)) = KG((2*(nEN(i1))-1),(2*(nEN(i2))-1)) + Ke(((2*i1)-1),((2*i2)-1));
and so on..

更多回答(1 个)

Cedric
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by