# Drawing a Tangent to a Spline

28 views (last 30 days)
Tb on 11 Feb 2021
Commented: Bjorn Gustavsson on 12 Feb 2021
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')
tangent1=m(xq(3))*(xq-xq(3))+y(3)
I get the error: 'Array indices must a positive integer or a logical value'
Thanks.

Bjorn Gustavsson on 11 Feb 2021
Edited: Bjorn Gustavsson on 11 Feb 2021
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
Bjorn Gustavsson on 12 Feb 2021
You're welcome.