改进了Matlab中的Euler方法

时间:2015-12-08 13:02:24

标签: matlab

是否有可能帮助我解决以下问题?

  

将局部和全局错误绘制为数字t的函数   对于Euler,h = 0.02的步长为h = 0.01t=0:1的解决方案   方法和Heun的“改进欧拉”方法。

我编写以下代码但不起作用:

   function [t,le,ge] = euler_errors(h)

   f=@(u) u*(2-u); % this is the function for the IVP
   t0=0;
   tn=1;
   t=t0:h:tn;%we want to find the errors along this solutions
   %here is the exact solution of the IVP
   u_exact=(0.2*exp(2*t))/(2+0.1*(exp(2*t)+1)); %the with initial value u(0)=0.1

   n=length(t);
   u_e=zeros(1,n);
   u_g=zeros(1,n);

   i=1;
   u_e(i)=0.1;
   u_g(i)=0.1;

   %u_e and u_g are both values given by Euler method 
   %u_e is for the local error 
   %u_g is for the global error
   while (i<n)
   u_e(i+1)=u_e(i)+h*f(u_e(i));
   u_g(i+1)=u_g(i)+h*f(u_exact(i));
   i=i+1;
   end;
   %le1 is the local error
   %ge1 is the global error
   le=abs(u_e-u_exact);
   ge=abs(u_g-u_exact);
   end

1 个答案:

答案 0 :(得分:1)

您使用mrdivide计算了u_exact,而不是使用按元素划分rdivide。这导致u_exact是标量,而不是在t的每个值处评估的向量。因此,您Index exceeds matrix dimensions i > 1只需./

要修复,请使用/而不是function [t,le,ge] = euler_errors(h) f=@(u) u*(2-u); % this is the function for the IVP t0=0; tn=1; t=t0:h:tn;%we want to find the errors along this solutions %here is the exact solution of the IVP u_exact=(0.2*exp(2*t))./(2+0.1*(exp(2*t)+1)); %the with initial value u(0)=0.1 n=length(t); u_e=zeros(1,n); u_g=zeros(1,n); i=1; u_e(i)=0.1; u_g(i)=0.1; %u_e and u_g are both values given by Euler method %u_e is for the local error %u_g is for the global error while (i<n) u_e(i+1)=u_e(i)+h*f(u_e(i)); u_g(i+1)=u_g(i)+h*f(u_exact(i)); i=i+1; end; %le1 is the local error %ge1 is the global error le=abs(u_e-u_exact); ge=abs(u_g-u_exact); end

InputStream

yay