Borrar filtros
Borrar filtros

For loop, two variables, and summation

1 visualización (últimos 30 días)
SeHee
SeHee el 19 de Ag. de 2014
Comentada: SeHee el 20 de Ag. de 2014
Hello, I want to solve one equation using matlab code, but continuously failed. The equation is like below (not exactly same, for j=1, another equation was used).
And my code is
a_homo=1;
K=[1 2 3; 4 5 6; 7 8 9];
n=[1; 2; 3];
for j=1:length(n);i=1:j-1;
if j==1;
ndot(j,1)=-n(j,1)*a_homo*(K(j,:)*n(:,1));
else
ndot(j,1)=0.5*a_homo*sum(K(i,j-i)*(n(i,1).*n(j-i,1)));
end
end
And the result that I wanted is like below
ndot=[-14; 0.5; 6];
come from
ndot(1,1)=-1*1*(K(1,1)*n(1,1)+K(2,1)*n(2,1)+K(3,1)*n(3,1))=-1*(1*1+2*2+3*3)=-14
ndot(2,1)=0.5*1*(K(1,1)*n(1,1)*n(1,1))=0.5*1=0.5
ndot(3,1)=0.5*1(K(1,2)*n(1,1)*n(2,1)+K(2,1)*n(2,1)*n(1,1))=0.5*(2*1*2+4*2*1)=0.5*(4+8)=6
But the result was
ndot=[-14; 0.5; 12]
How can I get the result that I want??
Please help me to solve this problem!Thanks in advance.
  2 comentarios
Doug
Doug el 19 de Ag. de 2014
The K(i,j-1) vector is 2x1, but you want it to be 1x2. Just take the transpose, sum(K(i,j-i)'*(n(i,1).*n(j-i,1)).
SeHee
SeHee el 20 de Ag. de 2014
Thank you, Doug. But sadly it doesn't work..

Iniciar sesión para comentar.

Respuesta aceptada

Pierre Benoit
Pierre Benoit el 20 de Ag. de 2014
Editada: Pierre Benoit el 20 de Ag. de 2014
If you look closely to what K(i,j-i) do, you will see it returns a sub-matrice that contains more that you really want. You only need the terms on the diagonal (which are in the matrice K, the j-2 antidiagonal).
With the code you wrote, you are doing this for j=3 ndot(3,1)=0.5*1(K(1,2)*n(1,1)*n(2,1)+K(2,1)*n(2,1)*n(1,1)) + K(1,1)*n(2,1)*n(1,1) + K(2,2)*n(1,1)*n(2,1) = 0.5*(2*1*2+4*2*1+1*2*1+5*1*2) = 12
I don't know if it's the fastest method to take the k-th antidiagonal but it doesn't seem important here.
a_homo=1;
K=[1 2 3; 4 5 6; 7 8 9];
n=[1; 2; 3];
ndot = zeros(length(n),1);
for j=1:length(n);
i=1:j-1;
if j==1;
ndot(j,1)=-n(j,1)*a_homo*(K(j,:)*n(:,1));
else
ndot(j,1)=0.5*a_homo*diag(K(i,j-i)).'*(n(i,1).*n(j-i,1));
end
end
  1 comentario
SeHee
SeHee el 20 de Ag. de 2014
Thank you so much for your helping and kind comment! I wish you have good luck in your life!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by