Borrar filtros
Borrar filtros

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

3 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Vitaly
Vitaly el 21 de Abr. de 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..

Más respuestas (1)

Cedric
Cedric el 21 de Abr. de 2013
Editada: Cedric el 21 de Abr. de 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 comentarios
Cedric
Cedric el 21 de Abr. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by