Effacer les filtres
Effacer les filtres

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

3 vues (au cours des 30 derniers jours)
Vitaly
Vitaly le 21 Avr 2013
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.

Réponse acceptée

Vitaly
Vitaly le 21 Avr 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..

Plus de réponses (1)

Cedric
Cedric le 21 Avr 2013
Modifié(e) : Cedric le 21 Avr 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 commentaires
Vitaly
Vitaly le 21 Avr 2013
thanks a lot
Cedric
Cedric le 21 Avr 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by