Drawing a Tangent to a Spline
4 views (last 30 days)
Show older comments
I am trying to draw a tangent at a point to the spline curve obtained through the interp1() function, however, I am having trouble with not being able to find the correct point in the gradient array corresponding to the point in the data array. Here is my code:
x = ([209, 907, 346, 908, 246, 457, 235, 232, 400]).^-1;
y = log10([9.6e20, 3.57e20, 3.3e20, 3.7e20, 2.7e21, 6.9e21, 5.7e21, 3.5e21, 7.8e22]);
xq = linspace(x(1), x(9), 20000)
yq = interp1(x,y,xq, 'spline')
plot(xq,yq,'blue')
m = gradient(yq, xq);
tangent1=m(xq(3))*(xq-xq(3))+y(3)
I get the error: 'Array indices must a positive integer or a logical value'
Please help.
Thanks.
0 Comments
Answers (1)
Bjorn Gustavsson
on 11 Feb 2021
Edited: Bjorn Gustavsson
on 11 Feb 2021
When you calculate the gradient:
m = gradient(yq, xq);
Then your m will have the same dimension as your xq and yq arrays. So when you want to calculate the tangent line from the point [xq(3),yq(3)] you need to use the corresponding element of your gradient array - that is the 3rd. You just have a typo in your code:
tangent1=m(xq(3))*(xq-xq(3))+y(3)
Should be:
tangent1 = m(3)*(xq-xq(3))+yq(3);
There you'll take the 3rd element out of m, and it should really be the 3rd element out of yq not out of y.
You should also avoid making it a habit of having numbered variables like tangent1 (why 1? At least make it 3?), start adapting to storing things like that in arrays that you can index to with a number later in your code instead of having numbered variables. Here you could chose between a cell-array for your tangents (+: you can use tangent-lines with different number of elements. -: slightly more cumbersome to use.) or a simple matrix (+: easier to compare different tangents, and displaying them at once. -: all better be same sized.)
HTH
6 Comments
See Also
Categories
Find more on Spline Postprocessing 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!