MATLAB: How to specify parameters to send to the ODE function when calling it using ode45

ode45orbit

I'm trying to write a general function to propagate an orbit from initial position and velocity vectors using ode45, but I want to be able to specify mu in the script from which I call the funtion (via ode45).
Here is the function I'm propagating:
function [xdot] = RVorbitPropogation(t, x)
r = sqrt((x(1))^2 + (x(2))^2 + (x(3))^2); %Define R

xdot = [x(4); x(5); x(6); -(mu/((r)^3))*x(1); -(mu/((r)^3))*x(2); -(mu/((r)^3))*x(3); mu;]; %Define equation

end
I want to specify mu in the script so I can use this function for different bodies. Here is where I call the function:
[R_converted,V_converted] = oe2rv(oe, mu);
y0 = [R_converted(1), R_converted(2), R_converted(3), V_converted(1), V_converted(2), V_converted(3)];
[T, Y] = ode45(@RVorbitPropogation,tspan, y0);
Is there a way to add another input to ODE45 for mu? I've tried using
function [xdot] = RVorbitPropogation(t, x, mu)
r = sqrt((x(1))^2 + (x(2))^2 + (x(3))^2); %Define R
xdot = [x(4); x(5); x(6); -(mu/((r)^3))*x(1); -(mu/((r)^3))*x(2); -(mu/((r)^3))*x(3); mu;]; %Define equation
end
and
[R_converted,V_converted] = oe2rv(oe, mu);
y0 = [R_converted(1), R_converted(2), R_converted(3), V_converted(1), V_converted(2), V_converted(3)];
[T, Y] = ode45(@RVorbitPropogation,tspan, y0);
but that doesn't work because of the way ode45 understands inputs. Thanks for the help!

Best Answer

This works:

function [xdot] = RVorbitPropogation(t, x, mu)
r = sqrt((x(1))^2 + (x(2))^2 + (x(3))^2); %Define R
xdot = [x(4); x(5); x(6); -(mu/((r)^3))*x(1); -(mu/((r)^3))*x(2); -(mu/((r)^3))*x(3); mu;]; %Define equation
end
mu = 42;                                                        % Create ‘mu’
tspan = [0 5];                                                  % Create ‘tspan’
y0 = [zeros(6,1); 1];                                           % Create ‘y0’
[T, Y] = ode45(@(t,x) RVorbitPropogation(t,x,mu),tspan, y0);
figure(1)
plot(T,Y)
grid

Note that in the ode45 call, ode45 only ‘sees’ the ‘(t,x)’ arguments, allowing the anonymous function call to ‘RVorbitPropogation’ to acquire ‘mu’ from the workspace.

Related Question