Trouble in ODE45 with "Array indices must be positive integers or logical values." error

조회 수: 5 (최근 30일)
Hello,
I can't seem to figure out how to get my inital condition right. I assume the code wants it at y(0), but I am given y(-0.5) = 1. Code is shown below:
tRange = [-0.5 0.62];
y(-0.5) = 1;
[tSol,ySol] = ode45(@odefun,tRange,y(-0.5))
plot(tSol,ySol)
%function shown below, it is local in my file
function dydt = odefun(t,y)
dydt = y + t;
end
It should be very simple, as I think I know how to use ode45 but then again, I keep hitting this wall. Any help is appreciated. Software version is R2021a.

채택된 답변

Bjorn Gustavsson
Bjorn Gustavsson 2021년 7월 8일
The initial condition variable, y in your case, should be an array with values for all components (in the case you solve a set of coupled ODEs) at the starting-time (whether that is at time zero or some other time or value of the independent variable). You should use:
y_at_minus_zerop5 = 1;
[tSol,ySol] = ode45(@odefun,tRange,y_at_minus_zerop5);
plot(tSol,ySol)
The name given here is just for illustrative purposes...
HTH
  댓글 수: 2
Noah Merriam
Noah Merriam 2021년 7월 8일
Thank you. However, if I continue my code and try to find the point at y(0.62) or the end point on the plot, I receive the same error.
tRange = [-0.5 0.62];
Y0 = 1;
[tSol,ySol] = ode45(@odefun,tRange,Y0);
plot(tSol,ySol)
Y62 = Y0(0.62)
Bjorn Gustavsson
Bjorn Gustavsson 2021년 7월 8일
The ODE-integrating functions either returns arrays for the time and the values of the solution at corresponding times, in your case some number of points between -0.5 and 0.62, or a solutions-struct with a couple of fields that you can learn about from the help and documentation of ode45 et al.. The solutions-struct can be used as input together with query-points-of-time to the function deval to calculate the solution at your times-of-interest. In the case you want the time at the final point you have that as the last element (rather the last row of elements) in the output ySol - that is:
y0p62 = ySol(end);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by