Matlab code to draw a tangent to a curve

∥☆過路亽.° 提交于 2019-12-08 05:49:02

问题


I need to draw a tangent to a curve at a particular point (say the point is chosen by the user). I have written a code that allows the user to manually pick up two points and then a line is drawn between them. But I would like to automate the process. Can someone please suggest any algorithms/already implemented matlab codes to do so?


回答1:


Try the function below. Of course, it needs lots of tweaking to apply to your case, but I think this is roughtly what you want.

function test

    hh = figure(1); clf, hold on
    grid on

    x = 0:0.01:2*pi;
    f = @(x) sin(x);
    fprime = @(x) cos(x);

    plot(x, f(x), 'r')
    axis tight

    D = [];
    L = [];
    set(hh, ...
        'WindowButtonMotionFcn', @mouseMove,...
        'WindowButtonDownFcn', @mouseClick);


    function mouseMove(varargin)

        coords = get(gca, 'currentpoint');
        xC = coords(1);

        if ishandle(D)
            delete(D); end
        D = plot(xC, f(xC), 'ko');

    end

    function mouseClick(obj, varargin)

        switch get(obj, 'selectiontype')

            % actions for left mouse button
            case 'normal' 

                coords = get(gca, 'currentpoint');
                xC = coords(1);
                yC = f(xC);

                a  = fprime(xC);
                b  = yC-a*xC;

                if ishandle(L)
                    delete(L); end
                L = line([0; 2*pi], [b; a*2*pi+b]);

            case 'alt'    
                % actions for right mouse button

            case 'extend' 
                % actions for middle mouse button

            case 'open'   
                % actions for double click

            otherwise
                % actions for some other X-mouse-whatever button

        end

    end

end


来源:https://stackoverflow.com/questions/13563931/matlab-code-to-draw-a-tangent-to-a-curve

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!