Compare the results with the ODE45 integrator:
[T, Y] = ode45(F, [0, tmax], s(:, 1).');
figure;
plot(T, Y);
figure;
plot(s.')
The trajectories are similar, but not equal. This is a problem of the too large step width h=0.1. As soon as you reduce the step width to h=0.01 the results become nearly equal. Your Runge Kutta seems to be fine.
while t < tmax create the last time point 10.1, not 10.0. For a constant step width prefer:
t = linspace(0, 3, round(3 / 0.1) + 1);
s = zeros(4, numel(t));
for i = 2:numel(t)
...
end
Letting an array grow iteratively requires a lot of resources nd can reduce the runtime dramatically. Therefore a pre-allocation of the output is a good programming practice.
Start the loop at time point 2, because at t(1) the initial values are defined already. The wrong last time point is a small inaccuracy, but it can be avoided easily.
This means that only the last component of tne numerator is divided, so a parenthesis is missing:
For the first term of the 3rd component you have
but in the publication there is:
Writing this formula in a a large unreadable line as an anonymous function makes it hard to debug. Don't do this. Prefer a dedicated function, which allows to split the parts and check them using the debugger:
function dF = DoublePendulum(t, s, m1, m2, l1, l2, g)
s12 = s(1) - s(2);
m12 = m1 + m2;
n1 = -m2 * l1 * s(3)^2 * sin(s12) * cos(s12) + g * m2 * sin(s(2)) * cos(s12) - ...
m2 * l2 * s(4)^2 * sin(s12) - m12 * g * sin(s(1));
d1 = l1 * m12 - m2 * l1 * cos(s12)^2;
n2 = m2 * l2 * s(4)^2 * sin(s12) * cos(s12) + g * m12 * sin(s(1)) * cos(s12) + ...
m12 * l1 * s(3)^2 * sin(s12) - m12 * g * sin(s(2));
d2 = l2 * m12 - m2 * l2 * cos(s12)^2;
dF = [s(3); ...
s(4); ...
n1 / d1, ...
n2 / d2];
end
Now the pattern of the two equations is visible on first sight and finding typos like the s(3) or s(4) is much easier.
Then define in your code:
F = @(t,s) DoublePendulum(t, s, m1, m2, l1, l2, g);
By the way: It is a drawback to obtain the dependent X/Y coordinates befor the integeration. Integrating the formulas for the angles is much faster and more accurate. Then the results can be used easily to compute the karthesian coordinates afterwards for the visualization. For a double pendulum both will work, but if you simulate > 4 connected pendulums the computing time with dependent coordinates explodes and the accuracy degrades.
Best Answer