Finding slope of a curve at some specific points
74 views (last 30 days)
Show older comments
Hi.
I did the sediment settling experiment and obtained the experimental data. My task is to calculate the average particle velocity. To compute this, I must calculate the average gradient of multiple gradients at different points. Can I know how to do this?
0 Comments
Accepted Answer
Star Strider
on 17 Apr 2023
Probably the easiest way to calculate the instantaneous slope is:
dydx = gradient(y) ./ gradient(x);
All that is necessary after that is to index into it by using the index of the appropriate ‘x’ values if those are known.
If the gradient is monotonic (either increasing or decreasing), it is straightforward to get the slope at any ‘x’ value using the interp1 function:
slope_at_xval = interp1(x, dydx, xval);
If the slopes are not monotonic, this is still possible, however the code becomes a bit more complicated.
.
6 Comments
Star Strider
on 17 Apr 2023
Sure!
It took a bit to adapt my previous code (using row vectors) to yours (using column vectors). This illustrates the derivatives by plotting tangents to the curves at random points —
% x = linspace(0, 4500, 1E+4);
% y = 85 - [80; 70; 60].*(1-exp(-[3;2;1]*0.001*x));
T1 = readtable('Data.xlsx', 'VariableNamingRule','preserve')
x = T1.Var1;
y = T1{:,2:4};
VN = T1.Properties.VariableNames;
[~,dy] = gradient(y); % Gradient Of 'y' Values
dydx = dy ./ gradient(x); % Derivative
xval = rand(1,3)*min(max(x)) % Choose 'x' Values (Can Be Any Appropriate Value)
for k = 1:size(y,2)
dydx_at_xval(:,k) = interp1(x, dydx(:,k), xval); % Calculate Derivatives AT 'xval'
y_at_xval(:,k) = interp1(x, y(:,k), xval); % Calculate 'y' Values At 'xval'
end
% dydx_at_xval
% y_at_xval
figure
plot(x, y)
hold on
for k1 = 1:size(y,2)
for k2 = 1:numel(xval)
b = y_at_xval(k2,k1)-dydx_at_xval(k2,k1)*xval(k2); % Calculate Tangent Line Y-Intercept
xrng = [-250 250]+xval(k2); % Tangent Line 'x' Range
tangent = xrng*dydx_at_xval(k2,k1) + b; % 'y' Values For Tangent Line
plot(xval(k2), y_at_xval(k2,k1), 'ms') % Plot Specific '(x,y)' Pair For Tangent Line
plot(xrng, tangent, '-r') % Plot Tangent Line
end
end
hold off
grid
xlabel('X')
ylabel('Y')
legend(VN{2:end}, 'Location','best')
I am not certain what you want with respect to the derivatives, however the data appear smooth so there are essentially no problems with noise. This illustrates the derivates as tangents to the curves at various points on the x-axis. If noise were a problem, the data would need to be smoothed first.
.
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices 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!