Implementing explicit Euler method (for ODEs) in MATLAB

怎甘沉沦 提交于 2019-12-02 22:56:38

问题


I've searched everywhere, and I can't find anything.

First of all, let me just say I have never used Mat Lab so I have no idea what I am doing what so ever.

I have tried a few things, but none have worked. Apparently y(0)=2 tries to create a list of 0 units with the value of 2?

Anyway, can someone help me? I need to write a flexible Euler's Method equation in Mat Lab to solve a few equations like this.

1) y' = 5-3sqrt(y) ; y(0)=2

With h= .1 , .05 , .025, .01 && t =.5 ,1 , 1.5 , 2 , 2.5 ,3

I have no idea what I am doing.


回答1:


Let us suppose to implement the method with constant time step, say dt>0. If we wanna integrate the equation up to a time T>0, we consider a time discretization

tt = 0:dt:T;

We'd better pre-allocate our solution vector for speed purpose, i.e.

yy=zeros(1,length(tt));

yy will contain the first order-in-time approximation of the solution we will produce (i.e., with little abuse of notation,

yy(1)==y_r(t=0)

and

yy(end)==y_r(t=T) + global error,

where the function y_r=y_r(t) is our real solution).

Supposedly, we have a first order ODE in normal form, i.e.

 dy_r / dt = f(y_r;t)

and an initial datum

 y_r(t=0)=y_0

(i.e. we have a Cauchy problem). Thus, we should firstly initialize our solution vector

  yy(1) = y_0;

then, we can find the solution for future times, i.e.

  N = length(tt);
  for t = 2 : N        // we should look at future times, thus we start from 2
                       // NOTE: this is first order explicit Euler scheme.
       yy(t) = yy(t-1) + dt*f(yy(t-1),t);
  end

We're done. We can now plot the solution.

  plot(tt,yy);

Now the point is: are you satisfied with first-order-in-time accuracy?

Think that if you use this scheme to solve e.g. Hamiltonian problems (say the simple harmonic oscillator), it will give artificial excitation to your system (properly, you can see a drift out of your correct Hamiltonian orbit). In few words, after little time your solution is completely artificial.

Indeed, when you solve real problems, you have to carefully consider your problem and your physics, and then choose a proper numerical scheme to solve your equation. Soon, probably you will be asked to implement more accurate schemes such as Runge Kutta (which you can better trust, but just a little bit, at least in their original form).



来源:https://stackoverflow.com/questions/13063060/implementing-explicit-euler-method-for-odes-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!