Matlab - how to draw a tangent along a curve

I plotted in a matrix with:

plot(x,y)

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

+3
source share
2 answers

If you do not have an explicit function for the constructed points, you can use finite differences to evaluate the derivative. For points not on the edge of the data range, the following applies:

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 this slope, it depends on what you want: only 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]);

or longer string

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

I am sure there are no errors in this code, but I will check it when I have Matlab;)

+2
source

, (y2-y1)/(x2-x1), plot() , . , y, , ( ), b y = mx + B.

+1

All Articles