MATLAB Answers

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

1 view (last 30 days)
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.

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 8 Jul 2021
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 Comments
Bjorn Gustavsson
Bjorn Gustavsson on 8 Jul 2021
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);

Sign in to comment.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!