Differential equations are at the heart of many real-world problems in science and engineering. Solving these equations numerically is often essential when analytical solutions are not readily available. One such numerical method is the Modified Euler's method, also known as Heun's method. In this blog post, we'll explore how to implement and use the Modified Euler's method in MATLAB.

In this blog, we will learn to program a Modified Euler’s method in MATLAB to solve ordinary differential equations. Also, we will dive into the MATLAB programming used to define the ODE as a custom function, calculate the intermediate steps using a for loop, and plot the results on a graph.

### Understanding the Modified Euler’s method?

The Modified Euler's method is a simple yet effective numerical technique for solving ordinary differential equations (ODEs). It belongs to the family of single-step, explicit methods, making it relatively straightforward to implement. This method is developed to provide more accurate results than Euler’s method. This method approximates the solution to an ODE by performing two main steps for each time increment-:

**Predictor Step:**Calculate a predicted value for the dependent variable (usually denoted as y) based on the current state. This prediction uses the formula of Euler’s method.

**Corrector Step:**Refine the prediction by taking an average of the slopes at the beginning and end of the time increment. For generating more accurate results, the below formula of Modified Euler’s method is used.

### Solving Differential Equations Analytically

#### Solved example of the Modified Euler’s method-:

Solve an ordinary differential equation , y=2 at x=0 by Modified Euler’s method and obtain y at x= 0.2 in two steps of 0.1 each.

**Solution:**

Given data, h = 0.1, x1_{ }= 0, y1_{ }= 2, x_{m}_{ }= 0.2

We have,

And we need to calculate y(0.2) =?

**Predictor Step 1 -:**

Calculate y2 at x1=0 using Euler’s method formula

Therefore,

…………….(1)

**Corrector Step 1 -:**

Calculate y2 at x2=0.1 using Modified Euler’s method formula

For the above formula of Modified Euler’s method use the y2 value from equation (1)

Iteration 1 -:

Iteration 2 -:

Iteration 3 -:

As we can see the value of y2 is repeating itself. So here, we stop doing iterations.

According to Modified Euler’s method, The value of

**= 1.9804 at x = 0.1 **………….....(2)

**Predictor Step 2 -:**

Calculate y3 at x2= 0.1 using Euler’s method formula

Therefore,

…………….(3)

**Corrector Step 2 -:**

Calculate y3 at x3=0.2 using Modified Euler’s method

For the above formula of Modified Euler’s method use the y3 value from equation (3)

Iteration 1 -:

Iteration 2 -:

Iteration 3 -:

As we can see the value of y3 is repeating itself at iteration no.3. So here, we stop performing iterations.

According to Modified Euler’s method value of **= 1.9238 at x = 0.2**

**ANS**** -: **So, here we can conclude that the value of y at x= 0.2 is found to be 1.9238

Therefore,

## Implementing Modified Euler’s method in MATLAB

We have solved the ordinary differential equation analytically using mathematical formulas and procedures, Now we will solve this problem with the help of MATLAB software. In the realm of numerical techniques for solving ordinary differential equations, the Modified Euler's method stands as a fundamental approach for approximating solutions. The Modified Euler's method takes a simpler yet effective approach, often referred to as the "predictor-corrector" method. Now, let's dive into the MATLAB code for employing the Modified Euler's method. Firstly, we will write the program by taking into account the data given in the problem and using the corresponding mathematical formula.

**Step 1: **

In this step, we will declare the standard commands that are used before starting any Script. These commands clear all the previous data in the command window as well as in the workspace.

- The (clc) command clears any previous input or output values in the command window.
- The (clear) command removes all the variables present in the workspace.
- The (format compact) command is used to reduce line spacing in the output displayed in the command window. This makes the output more compact and easier to read.
- The (close all) command closes all the previously opened tabs, such as graphs that are generated by earlier program executions.

% Standard commands for clearing any previous data

clc, clear, format compact, close all;

**Step 2:**

We will start by taking the input values from the user for the data that is already given in the problem. All of these values will be given as input to MATLAB by the user. The (input) function is used to assign the user-defined values to a specific variable.

- The (F) variable takes the given equation as an input, in the prescribed format.
- The (a) variable is assigned to the initial value of x i.e x1 [a = 0]
- The (b) variable is assigned to the initial value of y i.e y1 [b = 2]
- The (c) variable stores the value of x at which the value of y is to be calculated.[c = 0.2]
- The (h) is a variable that is assigned to the value of step size. [h = 0.1]

% Take user input for function f(x,y), step size(h) and initial values of x and y

F = input('Enter the given equation in the format as, @(x,y) equation: ');

a = input('Input the initial value of x: ');

b = input('Provide the initial value of y: ');

c = input('What is the value of x at which y is to be calculated: ');

h = input('Enter the value of step size h: ');

**Step 3: **

In this section of the code, we will declare some initial parameters with the " x " range.

- The variable “x” stores the values between ‘a’ and ‘c’ that are increasing by h, in the form of a matrix. Consider if the user inputs a=2, c=10 and h=2 in the command window, then x becomes [2 4 6 8 10].
- The initial value of y that was taken from the user and assigned to the variable ‘c’ in step 2, is now assigned to variable y as its 1
^{st}place value. - The anonymous/inline function that a user will input in the format as @(x,y) equation, is stored in variable “F”. Then at this point, the variable “F” value is assigned to the variable named “func”.
- The “@” sign is followed by the inputs (x,y). After some space, a user writes the ordinary differential equation given in the question.

% Declare the differential equation and initial values that are given as input by the user

func = F;

x = (a:h:c); %If the range of x is given then you can directly assign it here.

y(1) = b;

**Step 4:**

- In this section of code, two 'for loops' are employed to carry out Modified Euler's method for solving differential equations. The outer loop, denoted by 'for i,' iterates through the range of x values, which represent the independent variable. We predict an initial value of y within this loop using Euler's method.
- Here, the loop will run 2 times as the value of y(0.2) i.e., y3 is calculated using x2. The length of the “x” array is 3 because there are 3 elements in the matrix [0,0.1,0.2]. Therefore, the number of loops becomes (length of x -1), which is 2.

% Use for loop to Calculate values of y using Modified Euler's Method

for i = 1:(length(x) - 1)

% Calculate the predicted value of y using Euler's method

y_predi = y(i) + h * func(x(i), y(i));

% for loop is used below to calculate 3 iterations of corrected value

for n = 1:3

% Use the previous predicted value of y to calculate the new corrected value

y_corre = y(i) + (h / 2) * (func(x(i), y(i)) + func(x(i + 1), y_predi(n)));

y_predi(n+1) = y_corre;

end

% The value of y is updated for the next iteration

y(i + 1) = y_corre;

end

Inside this loop, we calculate an initial predicted value for y (denoted as 'y_predi') using Euler's method. This prediction is based on the slope of the function 'func' at the current point (x(i), y(i)).

Following this, another "for loop" (with the index variable 'n') is employed to refine the prediction. It calculates a sequence of corrected values for y (labelled as 'y_corre') in 3 iterations. The value for y_corre starts repeating itself after 3 iterations so, we have considered 3 iterations.

These corrections are made by adjusting 'y_predi' based on both the slope at the current point and the slope at the next point along the x-axis. The y_predi(n+1) = y_corre command assigns the recently calculated value of y_corre to the next iteration value of y_predi. The 'y_predi' values are updated iteratively in each inner loop, where each 'y_predi' is replaced by 'y_corre' as the corrected prediction for the next iteration.

Finally, the value of 'y' is updated to 'y_corre' for the next x value in the outer loop. This process continues for each x value in the specified range. The recently calculated and more accurate value of y_corre is assigned to “y” for the next iterative step.

By using these nested "for loops," the code calculates a series of corrected values to approximate the solution of the differential equation more accurately, applying the Modified Euler's method. The iterations refine the prediction with each step, improving the accuracy of the result.

**Step 5: **

Here we will store the values of x and y obtained from the loop, inside the two new variables X_values & Y_values. The double (x) function converts the values in x into double precision. This function is used to convert symbolic numbers into double-precision numbers. This step is used for simplicity in displaying the output and to assign the values of x and y accurately to the plot command.

% Collect output values of x and y in a matrix form for better representation

X_values = double(x)

Y_values = double(y)

**Step 6 :**

- This is the last part of the program where we plot the graph of results obtained from the above calculations. The x and y values up to the 3
^{rd}point are plotted on the x and y axes. - Supportive functions are also used to make the graph look more detailed and attractive.
- The plot function is used to plot a 2D graph, first x-axis values (X_values) are assigned, and then y-axis values (Y_values). Here the (-.or) command specifies the type of graph line to be used. In this case, a dashed dot line (-.) is used. (o) stands for the points on the graph that are highlighted by the circle. The (r) stands for the red colour of the line and circle on the graph.
- Next (‘linewidth’,1) function determines the thickness of the line that is drawn on the graph by joining the points.

% Plot the graph using the obtained values of x and y

plot(X_values, Y_values, '-.or', 'linewidth', 1)

% Supporting parameters of the graph for better visualization

title('Modified Eulers Method')

xlim([0, c]), ylim([min(Y_values)- 0.1, max(Y_values)+ 0.1])

xlabel('x value'), ylabel('y value')

grid on

The (title) function gives the heading to the graph, whereas the (xlim & ylim) defines the range of numbers on the two axes.

The min(Y_values)- 0.1 command takes the minimum value from the matrix named Y_values and subtracts 0.1 from it, which gives the starting point of the y-axis. Same is for the Max(Y_values).

Then the (xlabel & ylabel) functions provide a name or parameter to the x-axis and y-axis. Lastly, the (grid on) command makes the grid lines on the graph visible. These Commands are used to make the graph more informative.

### Output** **

The output of this MATLAB code is plotted on the graph and also shown in the command window. Enter the input parameters that are asked by the program. Input the differential equation in the format shown below. The values of x and y can be checked by simply clicking on the respective point on the graph. The variable “Y_values” stores the final answers of y.

Enter the given equation in the format as, @(x,y) equation: @(x,y) -x*y^2

Input the initial value of x: 0

Provide the initial value of y: 2

What is the value of x at which y is to be calculated: 0.2

Enter the value of step size h: 0.1

X_values =

0 0.1000 0.2000

Y_values = 2.0000 1.9804 1.9238

### Conclusion

- The Modified Euler's (Heun's) method) provides a simple yet effective way to solve ordinary differential equations numerically. With its straightforward implementation in MATLAB, it's a valuable tool for tackling a wide range of real-world problems in science and engineering. Whether you're studying chemical reactions, modelling population growth, or analyzing mechanical systems, Modified Euler's method can help you gain insights into dynamic processes.
- Throughout this blog post, we've explored the fundamental principles underlying the Modified Euler's method. We've learned how it refines predictions using two key steps: first, making an initial prediction with a basic Euler step, and then iteratively refining this prediction using corrector steps. This iterative approach enhances precision, making it particularly well-suited for systems with rapid changes. We've also witnessed how to translate this mathematical concept into functional MATLAB code.
- So, Start utilizing this powerful numerical method today and unlock the potential of ODE solving in MATLAB!