Matlab - 如何在曲线上绘制切线

时间:2012-05-23 21:22:09

标签: matlab

我在matlab中绘制了一个图表:

plot(x,y)

我的图形有不同的斜率,我如何在每个斜率上绘制切线并计算斜率系数?

2 个答案:

答案 0 :(得分:2)

如果您没有绘制点的显式函数,则可以使用finite differences来估算导数。以下内容适用于不在数据范围边界的点:

plot(x,y);
hold all;

% first sort the points, so x is monotonically rising
[x, sortidx] = sort(x);
y = y(sortidx);

% this is the x point for which you want to compute the slope
xslope = (x(1)+x(end))/2;

idx_a = find(x<xslope,1,'last');
idx_b = find(x>xslope,1,'first');
% or even simpler:
idx_b = idx_a+1;
% this assumes min(x)<xslope<max(x)

xa = x(idx_a);
xb = x(idx_b);
slope = (y(idx_b) - y(idx_a))/(xb - xa);

现在绘制斜率,取决于你想要的东西:只是一条短线:

yslope = interp1(x,y,xslope);
ya_sloped = yslope + (xa-xslope)*slope;
yb_sloped = yslope + (xb-xslope)*slope;
line([xa;xb],[ya_sloped;yb_sloped]);

或更长的行

yslope = interp1(x,y,xslope);
xa = xa + 4*(xa-xslope);
xb = xb + 4*(xb-xslope);
ya_sloped = yslope + (xa-xslope)*slope;
yb_sloped = yslope + (xb-xslope)*slope;
line([xa;xb],[ya_sloped;yb_sloped]);

我很确定此代码中没有错误,但是当我有matlab时我会测试它;)

答案 1 :(得分:1)

你必须弄清楚你感兴趣使用的任何点的斜率(y2-y1)/(x2-x1),然后使用plot()绘制一条具有该斜率的直线。要绘制直线,您需要y截距,并且因为您知道该直线上至少有一个点的坐标(这是您想要绘制切线的点),所以可以求解等式中的b y = mx + B.