Why my Gradient calculation shows anomaly?
7 views (last 30 days)
Show older comments
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.
0 Comments
Answers (1)
Epsilon
on 23 Sep 2024
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:
Link to the documentation on ‘smooth’ function: https://www.mathworks.com/help/curvefit/smooth.html?searchHighlight=smooth&s_tid=srchtitle_support_results_1_smooth
Hope it resolves the issue!
2 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!