MATLAB: For loop, two variables, and summation

for loopsum function

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.

Best Answer

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