老师说系统给的ode45好多都解决不了。
1.lorenz系统
test.m
clear;
clc;
%系统龙格库塔法
[t,h] = ode45(@test_fun,[0 40],[12 4 0]);
plot3(h(:,1),h(:,2),h(:,3));
grid on;
%自定义龙格库塔法
[t1,h1]=runge_kutta(@test_fun,[12 4 0],0.01,0,40);
figure;
plot3(h1(1,:),h1(2,:),h1(3,:),'r')
grid on;
runge_kutta.m
%参数表顺序依次是微分方程组的函数名称,初始值向量,步长,时间起点,时间终点(参数形式参考了ode45函数)
function [x,y]=runge_kutta(ufunc,y0,h,a,b)
n=floor((b-a)/h); %步数
x(1)=a; %时间起点
y(:,1)=y0; %赋初值,可以是向量,但是要注意维数
for i=1:n %龙格库塔方法进行数值求解
x(i+1)=x(i)+h;
k1=ufunc(x(i),y(:,i));
k2=ufunc(x(i)+h/2,y(:,i)+h*k1/2);
k3=ufunc(x(i)+h/2,y(:,i)+h*k2/2);
k4=ufunc(x(i)+h,y(:,i)+h*k3);
y(:,i+1)=y(:,i)+h*(k1+2*k2+2*k3+k4)/6;
end