MATLAB Answers

Chris
0

Need help using ODE45 and eulers function

Asked by Chris
on 5 Nov 2013
Latest activity Answered by Jonathan LeSage on 5 Nov 2013
Alright so I have this ODE I solved for it using ODE45 and now its asking me to modify my script by using a eulers method script that was given to us and use eulers to solve for it now. I am lost. If its confusinf at all let me know and i can try to clarify it.
Here is my ODE file
function ex_with_2eqs
t0 = 0; tf = 40; y0 = [-1;0];
[t,Y] = ode45(@f,[t0,tf],y0,[]);
y = Y(:,1);
v = Y(:,2);
figure(1);
plot(t,y,'b+',t,v,'ro')
legend('y(t)','v(t)=y''(t)');
title('Figure 1 L4g');
grid on;
ylim([-1.5,1.5]);
figure(2);
plot(y,v); axis square; xlabel('y'); ylabel('v');
title('Figure 2 L4g phase plot');
grid on;
ylim([-1.5,1.5]);
xlim([-1,1]);
end
Here is my function file
function dydt = f(t,Y)
y = Y(1);
v = Y(2);
dydt = [ v; cos(t)-4*y^2*v-3*y ];
end
and if it matters here is my eulers file although i know i dont have to do anything with it.
f
unction [te,Ye] = euler(f,tspan,y0,N)
% Solves the IVP y' = f(t,y), y(t0) = y0 in the time interval tspan = [t0,tf]
% using Euler's method with N time steps.
% Input:
% f = name of inline function or function M-file that evaluates the ODE
% (if not an inline function, use: euler(@f,tspan,y0,N))
% For a system, the f must be given as column vector.
% tspan = [t0, tf] where t0 = initial time value and tf = final time value
% y0 = initial value of the dependent variable. If solving a system,
% initial conditions must be given as a vector.
% N = number of steps used.
% Output:
% t = vector of time values where the solution was computed
% y = vector of computed solution values.
m = length(y0);
t0 = tspan(1);
tf = tspan(2);
h = (tf-t0)/N; % evaluate the time step size
t = linspace(t0,tf,N+1); % create the vector of t values
y = zeros(m,N+1); % allocate memory for the output y
y(:,1) = y0'; % set initial condition
for n=1:N
y(:,n+1) = y(:,n) + h*f(t(n),y(:,n)); % implement Euler's method
end
t = t'; y = y'; % change t and y from row to column vectors
end

  0 Comments

Sign in to comment.

1 Answer

Answer by Jonathan LeSage on 5 Nov 2013

It looks to me that you're nearly there! I found a couple of small mistakes that seems to be holding you back.
Changes to your code:
  • Replace ode45 with you defined euler function
  • Read the documentation of your euler function. Unlike ode45 which is a variable step numerical solver, Euler's method is a fixed step solver. As such, you need to specify the number of steps you want to take, N, as the final fuction input. I would imagine 250+ steps would be sufficient for this problem.
Changes to your euler function:
  • The two outputs of the function [te,Ye] are never defined in the code. From what I can tell, the outputs should be changes to [t,y].
Hope this helps to rectify the problem!

  0 Comments

Sign in to comment.