有时候不方便用MATLAB中自带的求解器,写一个定步长的四阶龙格库塔求解器。
四阶龙格库塔function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| function [t, y] = rungeKutta4(odefun, tspan, y0, h)
t0 = tspan(1); tf = tspan(2); t = t0:h:tf; n = length(t); y = zeros(length(y0), n); y(:,1) = y0; for i = 1:n-1 k1 = h * odefun(t(i), y(:,i)); k2 = h * odefun(t(i) + 0.5*h, y(:,i) + 0.5*k1); k3 = h * odefun(t(i) + 0.5*h, y(:,i) + 0.5*k2); k4 = h * odefun(t(i) + h, y(:,i) + k3); y(:,i+1) = y(:,i) + (k1 + 2*k2 + 2*k3 + k4) / 6; end end
|
二阶弹簧阻尼系统
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| function dx = damped_system(t, x) m=2; c=0.9; k=0.5; dx = zeros(2, 1); dx(1) = x(2); dx(2) = -(c/m) * x(2) - (k/m) * x(1); end
|
使用RK4求解二阶弹簧阻尼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| odefun = @damped_system;
tspan = [0, 20]; y0 = [0.1; 0]; h = 0.1;
[t, y] = rungeKutta4(odefun, tspan, y0, h);
figure; subplot(2, 1, 1); plot(t, y(1, :), '-o'); xlabel('Time t'); ylabel('x1(t)'); title('Solution of x1(t) using Runge-Kutta 4th order method'); grid on;
subplot(2, 1, 2); plot(t, y(2, :), '-o'); xlabel('Time t'); ylabel('x2(t)'); title('Solution of x2(t) using Runge-Kutta 4th order method'); grid on;
|
运行结果:
【MATLAB】 四阶龙格库塔求解器(以二阶弹簧阻尼系统为例)