For loop, two variables, and summation

3 views (last 30 days)
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 Comments
Doug
Doug on 19 Aug 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 on 20 Aug 2014
Thank you, Doug. But sadly it doesn't work..

Sign in to comment.

Accepted Answer

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

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!