MATLAB: How to draw the tangent to a curve passing through the origin


I have the following code
xt = -1:0.1:1;
and I get the blue curve as below. Now, I want to add a tangent line which must pass through the origin (as the black line I added "by hand" in the figure below).
I was thinking to use the function gradient but I am not sure how to impose the condition to pass through the (0,0).
Could you help me?

Best Answer

  • Assuming that you want to obtain tangent lines which pass through the (-110,0), how about the following?
    In this code, I changed delta xt from 0.1 to 0.01 in order to obtaion more accurate result.
    xt = -1:0.01:1;
    yt =-100-(2*(cos(xt)).^3)-(4*(cos(xt)).^2)-3*cos(xt);
    dyt = gradient(yt,0.01);
    % yt value of tangent line at xt = 0 for each point on the curve
    ytValue = yt - xt.*dyt;
    % Find the xt positions where ytValue is close to -110
    [~,pt] = mink(abs(ytValue + 110),2);
    % Tangent line
    ytTangent1 = dyt(pt(1))*(xt - xt(pt(1))) + yt(pt(1));
    ytTangent2 = dyt(pt(2))*(xt - xt(pt(2))) + yt(pt(2));
    % Draw the curve and the tangent line
    hold on
    grid on