Why my Gradient calculation shows anomaly?

I have an orginal curve in (X, Y) form in within a limited range (attached).
length(X) = length(Y) = 998
I increased the resolution and extended the range slightly by using PHIP function, as below:
Yintp = Y(1)-0.1:0.002:Y(end)+0.3;
Xintp = pchip(Y, X, Yintp);
Vector size is now, length(X) = length(Y) = 4298
I, then, calculated the gradients for both the orginal (1) and inteprolated (2) curves, as follows;
% Initialize an array to store the gradients
n = length(X);
m = length(Xintp);
gradients1 = zeros(n,1);
gradients2 = zeros(m,1);
% Calculate the forward difference for the first point
gradients1(1) = (X(2) - X(1)) / (Y(2) - Y(1));
gradients2(1) = (Xintp(2) - Xintp(1)) / (Yintp(2) - Yintp(1));
% Calculate the central differences for the middle points
for i = 2:n-1
gradients1(i) = (X(i+1) - X(i-1)) / (Y(i+1) - Y(i-1));
end
for i = 2:m-1
gradients2(i) = (Xintp(i+1) - Xintp(i-1)) / (Yintp(i+1) - Yintp(i-1));
end
% Calculate the backward difference for the last point
gradients1(n) = (X(n) - X(n-1)) / (Y(n) - Y(n-1));
gradients2(m) = (Xintp(m) - Xintp(m-1)) / (Yintp(m) - Yintp(m-1));
Displaying results in a figure
% Display the results
figure,
plot(Yintp,Xintp); grid on; hold on
plot(Y, X,'.b','DisplayName','Y vs X low res')
ylabel('X (cm)')
yyaxis right
plot(Y, gradients1,'-.r','DisplayName','Gradient - low res');
plot(Yintp, gradients2,'-', 'DisplayName','Gradient - high res');
ylabel('Y (cm)')
xlabel('Tangent Angle (deg)')
Problem 1: There is the discontinuity in the 'high res' gradient at the two ends, something not visible in the (X,Y) curves. Below are the expanded views:
Problem 2: Grandient data are noisy and noisiness increases with the resolution, as shown below:
Please help me figure out the dicontinuties in gradient calculations and create smooth gradients from the high res data.

回答(1 个)

Hi Sena,
The ‘smooth’ function can be used before calculating central differences to reduce the noise and improve the stability of the gradient estimates in the given data. To reduce the noise consider smoothening the original data as well.
Exemplar code to smoothen the original and the interpolated data:
X = smooth(X, 0.05, 'rloess');
Y = smooth(Y, 0.05, 'rloess');
Xintp = smooth(Xintp, 0.05, 'rloess');
Yintp = smooth(Yintp, 0.05, 'rloess');
The plot after smoothening:
Zoomed view with reduced noise:
Hope it resolves the issue!

2 个评论

Thank you Epsilon for the great help.
Smoothing factor of 0.05 seems to distort the curve but I will explore the optimal.
Yes you can do that, the above is just a typical example. Glad to help.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Interpolation 的更多信息

产品

版本

R2023b

提问:

2024-9-23

编辑:

2024-9-24

Community Treasure Hunt

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

Start Hunting!

Translated by