Remember that the ODE45 integrator has a stepsize controller, which can reject steps, if they are outside the error tolerance. Therefore storing the local positions inside the function to be integrated can reply invalid results. In addition the function to be integrated is called multiple times per step, such that you'd get more values of n than you get for the trajectory x. Afterwards it is not trivial to find out, which n belongs to which x.
Obtaining the values is much easier than with evil global variables which are known to cause more troubles than they solve:
function Main % clc; clear all; % No, do not clear all [t, x] = ode45(@funx1x2, [0 5], [0 0.5]); [dx, n] = funx1x2(t, x.'); figure; subplot(1,2,1); plot(t, x); subplot(1,2,2); plot(t, n, 'c'); end
function [dx, n] = funx1x2(t, x) S = 250; CC = 2.35; DD = 0.65; k = x(1, :); q = x(2, :); L = k * S * CC; D = q * S * DD; n = sqrt(L .^ 2 + D .^ 2); dx = [q; 0.5 * t * k]; end
Now funx1x2 is "vectorized": I accepts the input x as vector. Then the integrator calculates the trajectory at first and n is created for the evaluated time points afterwards. The 2nd output n is inored during the integration.
Another option would be to use the outputfcn, which is called for the accepted steps only, but this is more complicated.