How to add values to already existing ones in a matrix using for loop?

1 view (last 30 days)
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.

Accepted Answer

Vitaly
Vitaly on 21 Apr 2013
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..

More Answers (1)

Cedric
Cedric on 21 Apr 2013
Edited: Cedric on 21 Apr 2013
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 Comments
Cedric
Cedric on 21 Apr 2013
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.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!