Azzera filtri
Azzera filtri

For loop, two variables, and summation

1 visualizzazione (ultimi 30 giorni)
SeHee
SeHee il 19 Ago 2014
Commentato: SeHee il 20 Ago 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 Commenti
Doug
Doug il 19 Ago 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 il 20 Ago 2014
Thank you, Doug. But sadly it doesn't work..

Accedi per commentare.

Risposta accettata

Pierre Benoit
Pierre Benoit il 20 Ago 2014
Modificato: Pierre Benoit il 20 Ago 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 Commento
SeHee
SeHee il 20 Ago 2014
Thank you so much for your helping and kind comment! I wish you have good luck in your life!

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by