0% found this document useful (0 votes)
9 views

Labwork 6

Uploaded by

vietnc.23bi14449
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Labwork 6

Uploaded by

vietnc.23bi14449
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

%% exercise 5

% Function for the ODE


function yprime = yprime(t, y)
yprime = t^2 + y;
end

% Exact solution
y_exact = @(t) 3*exp(t) - t.^2 - 2*t - 2;

% Euler method implementation


function [t_values, y_values] = euler_method(h, t_end, y0)
t_values = 0:h:t_end;
y_values = zeros(size(t_values));
y_values(1) = y0;
for i = 2:length(t_values)
y_values(i) = y_values(i-1) + h * yprime(t_values(i-1), y_values(i-1));
end
end

% Initial condition and time span


y0 = 1;
t_end = 2;

% Step sizes
h_values = [0.5, 0.25, 0.1, 0.01];

% Plotting the results


figure;
hold on;
for h = h_values
[t_values, y_values] = euler_method(h, t_end, y0);
plot(t_values, y_values, 'DisplayName', ['h = ' num2str(h)]);
end

% Plot exact solution


t_exact = linspace(0, t_end);
y_exact_values = y_exact(t_exact);
plot(t_exact, y_exact_values, 'k', 'LineWidth', 2, 'DisplayName', 'Exact
Solution');

% Formatting the plot


xlabel('t');
ylabel('y');
title('Euler Method Solutions with Different Step Sizes');
legend;
hold off;
%% exercise 1 6b
% Define parameters
h = 1; % step size
t0 = 0; % initial time
y0 = 2; % initial condition
t_end = 4; % end time

% Number of steps
N = (t_end - t0) / h;

% Initialize arrays to store results


t = t0:h:t_end;
y = zeros(1, N+1);
y(1) = y0;

% Euler's method loop


for n = 1:N
% Compute the derivative
f = @(t, y) 4*exp(0.8*t) - 0.5*y;

% Update y using Euler's method


y(n+1) = y(n) + h * f(t(n), y(n));
end

% Display the results


disp('t values:')
disp(t)
disp('y values:')
disp(y)

% Plot the numerical solution


plot(t, y, '-o')
hold on

% Plot the exact solution for comparison


exact_solution = @(t) (4/1.3)*(exp(0.8*t) - exp(-0.5*t)) + 2*exp(-0.5*t);
fplot(exact_solution, [t0 t_end], 'r')
legend('Euler Method', 'Exact Solution')
title('Euler Method vs Exact Solution')
xlabel('t')
ylabel('y')
hold off
%% exercise 2 6b
% Define the ODE as a function
ode = @(t, y) 2*t;

% Set the time interval


tspan = [0 5];

% Set the initial condition


y0 = 0;

% Solve the ODE using ode45


[t, y] = ode45(ode, tspan, y0);

% Plot the solution


plot(t, y, '-o')
xlabel('Time t')
ylabel('Solution y')
title('Solution of ODE y'' = 2t using ode45')
grid on

You might also like