3

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

plot(x,y)

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

4

2 回答 2

2

如果您没有绘制点的显式函数,则可以使用有限差分来估计导数。以下适用于不在数据跨度边界上的点:

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 时我会对其进行测试;)

于 2012-05-23T21:46:48.370 回答
1

您必须计算出您有兴趣使用 (y2-y1)/(x2-x1) 的任何点的斜率,然后使用 plot() 绘制一条具有该斜率的直线。要绘制直线,您需要 y 截距,并且由于您知道该直线上至少一个点的坐标(这是您要绘制切线的点),您可以在方程 y=mx 中求解 b +b。

于 2012-05-23T21:37:58.960 回答