Write a function M-file my_euler.m which take 5 input values, f, t_0, y_0, dt, and t_f that specify the function to be approximated, the initial t-value, the initial condition y(t0)=y0, the step-size Δt, and the final t-value at which you want to approximate the solution y(t). Your function should:
By using this code, modify it. All variables inside my_euler.m the should be calculated from the input variables so that you can run the function from the Command Window.
t = zeros(1,8+1);
y = zeros(1,8+1);
t(1) = 1;
y(1) = 0;
dt = 0.25;
for k = 1:8
t(k+1) = t(k)+dt;
y(k+1)=y(k)+dt*f(t(k),y(k));
f = @(t,y)(2*t*exp(-1/t) +y/t^2);
end
plot(t,y,'ro-')
t(end)
y(end)
function yn = my_euler(f,t_0,y_0,dt,t_f)
t=t_0:dt:t_f;
y=zeros(1,length(t));
y(1)=y_0;
for i = 2:length(y)
y(i)=y(i-1)+dt*f(t(i-1),y(i-1));
end
yn=y(end);
plot(t,y,'r-+','MarkerEdgecolor','g')
end
Get Answers For Free
Most questions answered within 1 hours.