For loop, two variables, and summation

3 vues (au cours des 30 derniers jours)
SeHee
SeHee le 19 Août 2014
Commenté : SeHee le 20 Août 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 commentaires
Doug
Doug le 19 Août 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 le 20 Août 2014
Thank you, Doug. But sadly it doesn't work..

Connectez-vous pour commenter.

Réponse acceptée

Pierre Benoit
Pierre Benoit le 20 Août 2014
Modifié(e) : Pierre Benoit le 20 Août 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 commentaire
SeHee
SeHee le 20 Août 2014
Thank you so much for your helping and kind comment! I wish you have good luck in your life!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

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

Community Treasure Hunt

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

Start Hunting!

Translated by