Reputation: 49
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?
Upvotes: 3
Views: 20789
Reputation: 11168
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]);
or a longer line
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'm pretty sure there're no bugs in this code, but I'll test it out when I have matlab around ;)
Upvotes: 2
Reputation: 1271
You'll have to figure out the slope at whatever points you're interested in using (y2-y1)/(x2-x1) and then use plot() to draw a straight line that has that slope. To draw the line, you need the y intercept, and since you know the coordinates of at least one point on that line (which is the point you want to draw the tangent to), you can solve for b in the equation y=mx+b.
Upvotes: 1