plot the euler method when when h=0.1 and h=.001 in matlab in matlab

To plot the Euler method in MATLAB for two different step sizes, you can use the following code:

main.m
% Define the parameters and initial conditions
h1 = 0.1;   % Step size 1
h2 = 0.001; % Step size 2
t0 = 0;     % Initial time
y0 = 1;     % Initial condition

% Define the differential equation
f = @(t, y) -t*y;

% Define the function for Euler method
euler = @(t, y, h) y + h * f(t, y);

% Compute the solutions for the two different step sizes
t1 = t0:h1:1;     % Time steps for step size 1
t2 = t0:h2:1;     % Time steps for step size 2
y1 = zeros(size(t1));   % Array to store the solutions
y2 = zeros(size(t2));   % Array to store the solutions
y1(1) = y0;       % Initial condition for step size 1
y2(1) = y0;       % Initial condition for step size 2

% Perform the Euler method for step size 1
for i = 1:length(t1)-1
    y1(i+1) = euler(t1(i), y1(i), h1);
end

% Perform the Euler method for step size 2
for i = 1:length(t2)-1
    y2(i+1) = euler(t2(i), y2(i), h2);
end

% Plot the solutions
plot(t1, y1, 'b-', t2, y2, 'r--');
legend(['h = ', num2str(h1)], ['h = ', num2str(h2)]);
xlabel('t');
ylabel('y');
title('Euler Method Solutions');
grid on;
1057 chars
38 lines

Make sure to replace the differential equation f and the initial condition y0 as per your requirements. After running this code, you should get a plot showing the solutions for the two different step sizes.

Note: The code assumes that you want to compute the solutions for the time interval [t0, 1]. You can modify the range by changing the values of t0 and the upper limit in the t1 and t2 calculations.

Hope this helps!

related categories

gistlibby LogSnag