I understand that you are trying to visualize how the error behaves with respect to the step size when using the Euler method.
I extended your original code by making the following additions:
- A loop over different step sizes (n values like 5, 10, 20, ...).
- Computation of the global error at the final time point (t = 1) for each step size.
- A log-log plot to visualize the relationship between the step size (‘h’) and the error.
You can find the code below for better understanding of the changes:
clc; clear; close all;
% Define the exact solution function for your reference
yt = @(t) 3.*exp(t.^2/2) - t.^2 - 2;
% Interval and initial condition calculations
inter = [0, 1];
y0 = 1;
% Vector of different n (number of steps)
n_values = [5, 10, 20, 40, 80, 160, 320];
h_values = zeros(size(n_values));
error_values = zeros(size(n_values));
% Now, we'll iterate over different step sizes
for k = 1:length(n_values)
n = n_values(k);
h = (inter(2) - inter(1)) / n;
h_values(k) = h;
% using Euler method
t(1) = inter(1);
y(1) = y0;
for i = 1:n
t(i+1) = t(i) + h;
y(i+1) = y(i) + h * ydot(t(i), y(i));
end
% Compute error at final point
exact = yt(inter(2));
approx = y(end);
error_values(k) = abs(approx - exact);
end
% Plot error vs step size on log-log scale
figure;
loglog(h_values, error_values, 'o-r', 'LineWidth', 2, 'MarkerSize', 8);
grid on;
xlabel('Step size (h)');
ylabel('Error at t = 1');
title('Error vs Step Size (Euler Method)');
legend('Error');
% Plot approximate vs exact solution for the finest step
figure;
plot(t, y, '-', 'DisplayName', 'Euler Approximation');
hold on;
fplot(yt, [inter(1), inter(2)], 'k--', 'DisplayName', 'Exact Solution');
xlabel('t');
ylabel('y');
title('Euler Approximation vs Exact Solution');
legend;
grid on;
function z = ydot(t, y)
z = t .* y + t.^3;
end
I am also attaching the documentation links of the functions used for reference:
- “loglog”: for plotting data on a logarithmic scale for both x and y axes. https://www.mathworks.com/help/matlab/ref/loglog.html
- “abs”: for computing the absolute values. https://www.mathworks.com/help/matlab/ref/double.abs.html
- “legend”: for adding legends to the plots. https://www.mathworks.com/help/matlab/ref/legend.html