How to Use Euler's Method in MATLAB

Analytic methods cannot be used for finding the exact solution for a differential equation of the form dP/dt = f(P) in most situations. Therefore, numerical methods, such as the Euler's method, were invented to help obtain a proper approximation of the solution of such an equation. MATLAB provides functions that allow users to easily implement this method and solve differential equations with just a few lines of code.

Instructions

    • 1

      Compute delta t with MATLAB. Since, by using Euler's method, dP/dt can be written as (Pn + 1 -- Pn)/delta t, first decide on this value to obtain your approximation. All you need to do is define the solving time, as well as the number of time intervals, and divide them to obtain delta t. An example is as follows:

      t = 5;

      n = 50;

      deltat = t/n;

    • 2

      Set a value for all the parameters of the equation. If, for example, you would like to implement Pn + 1 = Pn + x * delta t * Pn, you would only need to define x in MATLAB, since delta t was already defined in the previous step:

      r = .01;

    • 3

      Create an array that you will be using to compute your solutions. Fill it with 0 and set a starting value as follows:

      P = zeros (1, n + 1);

      P(1) = 2;

    • 4

      Use a "for" loop to obtain the Euler's solution recurrently. Make sure you also use the "end" command to avoid compile errors.

      for i = 1:n

      P(i+1) = P(i) * (1 + x * deltat);

      end

    • 5

      Plot the solution in order to visualize it. This step is optional, but you will have a clearer view of your approximation if you do it. You can use the "plot" function as follows:

      plot (linspace(0,t,n+1), p)

Learnify Hub © www.0685.com All Rights Reserved