2
votes

I am looking for a compact and efficient way to tackle the following problem. I have a system of differential equation, say 3, and I want to extend it for a molecular dynamics type calculation.

Currently this is the starting point

function dy = molec(t,y)
dy = zeros(3,1);
A = 1;
B = 1;
dy(1) = (A/B)*   (2 * (y(2)-y(1)) - 0.5) ;
dy(2) = (A/B)*  (  2* ( y(1) - y(2) )  + 4* (y(3)-y(2))    )     ;
dy(3) = (A/B)*  ( 6 * (- y(3)) + 4 * (  y(2) - y(3) )    );

I would like to have overall 100-150 variables. I could add further dy(n) definitions by typing them but it is hardly practical. I would like instead to take advantage of the recursive definition of the problem. Indeed, given a known sequence a_n, the n-th term is defined

dy(n) = (A/B)* a_n*(y_{n-1} - y{n}) + a_{n-1}*y_{n+1} - y_{n})

Any help would be so appreciated, thanks

1

1 Answers

1
votes

This is rather an iterative definition, nothing recursive inside it.

Use something like

diff = y(2:N)-y(1:N-1)
dy(1:N-1)=a(1:N-1) .* diff
dy(2:N) = dy(2:N) - a(2:N) .* diff
dy(1) = dy(1) + ...
dy(N) = dy(N) + ...
dy = dy * (A/B)

or a for loop that directly implements your formula.