Tangent on a curve
조회 수: 61(최근 30일)
I have a plot (along with data which I plotted) pasted above. I have to draw two tangents at different points A and B and should find the C ( the coordinates at which they meet).
It would be great if anyone can help me. How can I do it?
Priysha LNU 2020년 10월 8일
You'll need to fit a function to the data and then take its derivative. Let x and y be the two lists of data points. First, the fit:
n = 10;
[p,~,mu] = polyfit(x,y,n); % degree 10 polynomial fit, centered and scaled
% Plot the fit with the data
xfit = linspace(min(x),max(x),100);
yfit = polyval(p,xfit,,mu);
Now you can use a numerical derivative to calculate the tangent. You may download the package Adaptive Robust Numerical Differentiation package from the File Exchange. Then you may do the following:
idx = input(['Enter index in the range ',num2str([1 length(x)]),':']);
x0 = x(idx);
f = @(x) polyval(p,x,,mu);
df = derivest(f,x0); % Here is the derivative
% Calculate the end points of a tangent line
xt = [x0-0.05 x0+0.05];
yt = f(x0) + (xt-x0)*df;
DISCLAIMER: These are my own views and in no way depict those of MathWorks.