I am trying to simulate a particle that will move around a circumference randomly. The way I do that is by generating a random position profile and then interpolating it. I need to calculate the velocity and acceleration, which I do with the gradient
function over time discretization dt
. Since I need to limit the maximum acceleration of the system, I first smooth the position profile, but some singular points appear on the curve, so the derivatives are no longer continuous. Of course, there's no physical reason for that and I would like to make all derivatives smooth.
What I have tried is to smooth the position profile a second time in order to try to eliminate said singular points, but even though they are greatly reduced, velocity and acceleration are not completely smooth. I'll attach some pictures of the profiles.
T_exp = 100; %time of experiment
dt = 0.01;
%%Random profile generation
theta_rough = 4*pi*rand(1,T_exp)-2*pi; %random position profile
abscissa = 1:1:T_exp;
T_int = 1:dt:T_exp;
theta = interp1(abscissa,theta_rough,T_int,'spline'); %interpolated profile (not yet smooothed)
theta_smooth = smooth(theta,0.1,'rloess'); %interpolated and smoothed random profile
theta_smooth = smoothdata(theta_smooth,'sgolay'); %second, softer smoothing
theta_dot = gradient(theta_smooth, dt); %velocity profile
theta_2dot = gradient(theta_dot, dt); %acceleration profile
%%Plotting
figure (1)
plot(T_int, theta_smooth)
hold on
plot(T_int, theta_dot)
plot(T_int, theta_2dot)
hold off
grid on
legend('theta','theta dot','theta 2 dot')
After thinking about it for a while I realized that I didn't fully understand the nature of what interp1
does when it uses a spline. A spline is a C2 function, which means that the second derivative exists and is continuous, but not necessarily smooth. Thus, when interpolating position and differentiating twice, I get those 'weird' shapes in the velocity and acceleration profiles, which are perfectly understandable from a physical perspective.
As a result, no amount of smoothing will change the nature of the spline, and so the solution is to either use a C3 function or to integrate the position from the acceleration, as commented by Wolfie.