At what point do you want to plot the tangent?
The usual approach is to use the gradient function to find the slope, then use that and the value of the function at that point to calculate the intercept. The slope and intercept then define the tangent line at that point.
Example —
x = linspace(0, 5);
y = x.^2;
h = x(2)-x(1);
dydx = gradient(y, h);
xi = 2.1;
yi = interp1(x, y, xi);
dydxi = interp1(x, dydx, xi);
intcpt = yi - dydxi*xi;
figure
plot(x, y, '-b')
hold on
plot(x, dydxi*x+intcpt, '-r')
hold off
grid
legend('Data','Tangent', 'Location','NW')
EDIT —
To clarify my approach, I choose to use interp1 and gradient simply because it allows the desired ‘x’ value to be any value between the limits of the x-axis.
Best Answer