Matlab-如何在曲线上绘制切线 [英] Matlab - how to draw tangent on curve

查看:2010
本文介绍了Matlab-如何在曲线上绘制切线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在matlab中用以下方式绘制了一个图形:

I have plotted a graph in matlab with:

plot(x,y)

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

and my graph has different slopes, how do i draw tangents on each slope and calculate the coefficient for the slope?

推荐答案

如果绘制点没有明确的功能,则可以使用

If you don't have an explicit function for the plotted points, you can use finite differences for estimating the derivative. The following is appropriate for points not on the border of the data span:

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);

现在绘制该斜率,取决于您想要的内容:仅需短线:

Now drawing that slope, it depends on what you want: just a short line:

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

I'm pretty sure there're no bugs in this code, but I'll test it out when I have matlab around ;)

这篇关于Matlab-如何在曲线上绘制切线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆