# How to normalize state variables in ODE45 each timestep.

6 views (last 30 days)
Dario Muller on 26 Nov 2021
Answered: Paul on 26 Nov 2021
I am currently working on a dynamic simulation using ODE45 where I am using euler parameters (normalized quaternions) and I need to normalize them each time step in order to keep the simulation acurate.
From my understanding, when using ODE45 I will pass it a function which outputs the time derivative of each state variable at whatever timestep is input. This gives me control over the time derivatives of my euler parameters, but not the parameters themselves as the integrator takes care of that.
Is there any way of having the integrator take these four parameters and normalize them after each time step to keep their magnitude equal to 1?
Essentially, I would like it to run the following function after each time step and before the next one:
function q_norm = q_normalizer(q0,q1,q2,q3)
q_norm = [q0;q1;q2;q3]/norm([q0;q1;q2;q3]);
end
Where q0,q1,q2,q3 are all some subset of the state variables stored in my state variable vector y which the integrator iterates over.
This is crucial to maintain the acuracy rotation matrices used in the simulation using this method.
Can this be done in ODE45 or should I switch to a different solver? Currently the documentation on ode45 has not given me any leads on this, since a variable time-step solver should not be an issue for something like this.
Thank you,

Paul on 26 Nov 2021
Some thoughts:
a. If you know from the application that you don't have to worry about getting close to singularities, integrate three rotation angles instead of the quaternion and then compute the rotation matrices directly from the angles, or
b. in odefun, normalize q before doing any computations with it, including computing qdot, or
c. Use an event detection function to capture when norm(q) is too far from unity, stop the simulation, normalize q, and then continue.
And don't foget that the solver error tolerances will affect the accuracy of the solution.

R2021b

### Community Treasure Hunt

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

Start Hunting!