ODE45 how do I interpret this code...

3 views (last 30 days)
Douglas Alves
Douglas Alves on 13 May 2014
Commented: Sara on 13 May 2014
if true
% code
end
function elements
tspan = [0 1];
inits = [0 1];
[t,y] = ode45(@Y,tspan,inits);
plot(t,y)
function deriv = Y(t,y)
deriv = zeros(size(y));
deriv(1) = y(2) ;
deriv(2) = -y(1);
% the same as deriv = [y(2); -y(1)]
The first part I understand y is created and initiate with a vector [ 0 1 ] which is the initial condition. However the part deriv(1) = y(2) and the following line confuses me. I think that since y was created when matlab goes to the function deriv it will see the function as deriv(1) = 1 and deriv(2) = -0 since y exists... However the code works and matlab sees the function ( I mean the Y's ) as variables y1 and y2 ... Could anyone clarify this to me please. How does MATLAB read this... Sorry that's my second question about it. I don't think I got it.. I've already read doc ode45 and doc function it's not clear in there.

Accepted Answer

Sara
Sara on 13 May 2014
When you call an ode solver, the values of y passed to your function Y change in time and depend on numerical method, in this case a Runge-Kutta.
The mathematical meaning of the code is that, given 2 variables y1 and y2, then their derivatives in time can be written as:
dy1/dt = y2
dy2/dt = -y1
What system this is I have no idea.
What is your problem with this code??
  2 Comments
Douglas Alves
Douglas Alves on 13 May 2014
The code is ok. But I don't get the syntax. Because y is defined by the initial values. And it happens before I enter ode45 so when the function Y is called there must be an erro because instead of y(2) be a variable it could be the second element of y .. Why not? See my confusion?
Sara
Sara on 13 May 2014
"because instead of y(2) be a variable it could be the second element of y" ... I don't get what you mean with this.
You don't go directly from your code to the Y function. You pass the initial conditions to ode45 and a time range, then ode45 calls Y as many times as needed with different values of y (where y is an array of 2 elements, corresponding to 2 different variables). Do you have know what a Runge-Kutta is? What the ode45 does is calculating the evolution in time of y(1) and y(2).

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!