Displaying values of x, ode45 and real y in a fprintf command

1 view (last 30 days)
Hi, I was messing aroung ode45 and the example provided in
openExample('matlab/ODE23PassExtraArgumentsToODEFunctionExample').
However, I am trying to include a fprintf of the values of 'x,' 'y' and the values calculated by 'ode45.' Is there a way we can fprinf all three of them in the command window like in the code below? With that in mind I wanted to consult which of the graphs is the ode45?
I would very much appreciate the help.

Accepted Answer

Walter Roberson
Walter Roberson on 24 Oct 2021
Yes and no.
Yes, you can include an fprintf() statement inside your ode function, and that fprintf() statement will display whatever you ask it to display.
However... it is unlikely to be what you want.
ode45() and similar routines are adaptive routines. They internally propose a new time and new values for the boundary conditions. They then evaluate the ode function at that point and at a number of other nearby points, and put those together according to a mathematical relationship. If they guessed correctly, then the value predicted by the mathematical relationship will be "close to" the value implied by the proposed new location, and that proposed location is "accepted" as the new location. But if the predicted value is too far from the value implied by the proposed new location, then that step is "rejected", and the ode* function tries again with a smaller step size.
Now... if you put in an fprintf() then that fprintf() is going to be evaluate for every invocation of the ode function -- including not only the rejected steps but also the evaluations at the "nearby" places.
Furthermore... the ode*() functions can emit outputs that were never explicitly evaluated at. For example if you asked it to output at time 0.3 and the current time is 0.2937 then ode45() might decide that it is "close enough" and project what it imagines would be the outputs at 0.3 without evaluating at that exact place.
Because of these factors, it is often much better to not fprintf() inside the ode functions (except for debugging), and to not even try to save the values of internal variables. Instead, take the pair of outputs from the ode*() routines, and either directly display those (if appropriate) or else have code that re-creates the values of any internal variables that would correspond to those inputs.
  2 Comments
Juan Romero
Juan Romero on 24 Oct 2021
Hi,
thanks for the feedback! I'll take this into account. I'll see if there are any alternatives, since I did want to use Runge-Kutta 4th order to solve second order ode's. Either way, I'll take it into account, Thank you very much.
Kind regards.

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!