实例:
u'=-3u+6x+5
u(0)=3
解析解:u=2e^(-3x)+2x+1
欧拉法
h=0.01;%步长
x=0:h:1;
u=zeros(length(x),1);
u(1)=3;
for i=1:length(x)-1
du=-3*u(i)+6*x(i)+5;
u(i+1)=u(i)+h*du;
end
figure(1)
U=2*exp(-3*x)+2*x+1;
plot(x,U,'r')%解析解
hold on
plot(x,u,'bo','MarkerFaceColor','b')%数值解
改进的欧拉法
clc
clear
h=0.01;%步长
x=0:h:1;
u=zeros(length(x),1);
u(1)=3;
for i=1:length(x)-1
du=-3*u(i)+6*x(i)+5;
u_ba=u(i)+h*du;
du1=-3*u_ba+6*x(i+1)+5;
u(i+1)=u(i)+h*0.5*(du+du1);
end
hold on
plot(x,u,'k^','MarkerFaceColor','k')
ode45求解
function dudt=odefun(x,u)
dudt=-3*u+6*x+5;
end
clc
clear
xspan=0:0.01:1;
u0=3;
[x,u] = ode45('odefun', xspan, u0);
hold on
plot(x,u,'bs','MarkerFaceColor','b')
总体
function dudt=odefun(x,u)
dudt=-3*u+6*x+5;
end
clc
clear
h=0.01;%步长
x=0:h:1;
u=zeros(length(x),1);
u(1)=3;
for i=1:length(x)-1
du=-3*u(i)+6*x(i)+5;
u(i+1)=u(i)+h*du;
end
figure(1)
U=2*exp(-3*x)+2*x+1;
plot(x,U,'r')
hold on
plot(x,u,'bo')
for i=1:length(x)-1
du=-3*u(i)+6*x(i)+5;
u_ba=u(i)+h*du;
du1=-3*u_ba+6*x(i+1)+5;
u(i+1)=u(i)+h*0.5*(du+du1);
end
hold on
plot(x,u,'go')
xspan=0:0.01:1;
u0=3;
[x,u] = ode45('odefun', xspan, u0);
hold on
plot(x,u,'go')
legend('解析解','欧拉法的解','改进欧拉法的解','ode45')