필터 지우기
필터 지우기

Drawing a Tangent to a Spline

조회 수: 11 (최근 30일)
Tb
Tb 2021년 2월 11일
댓글: Bjorn Gustavsson 2021년 2월 12일
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.

답변 (1개)

Bjorn Gustavsson
Bjorn Gustavsson 2021년 2월 11일
편집: Bjorn Gustavsson 2021년 2월 11일
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
Tb
Tb 2021년 2월 11일
Oh yes that makes sense, and that works now as well. Thanks a lot.
Bjorn Gustavsson
Bjorn Gustavsson 2021년 2월 12일
You're welcome.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Spline Postprocessing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by