【问题标题】:Matlab code to draw a tangent to a curveMatlab代码绘制曲线的切线
【发布时间】:2012-11-26 11:30:27
【问题描述】:

我需要在特定点绘制一条曲线的切线(假设该点由用户选择)。我编写了一个代码,允许用户手动选择两个点,然后在它们之间画一条线。但我想自动化这个过程。有人可以建议任何算法/已经实现的 matlab 代码吗?

【问题讨论】:

  • 嗯,这取决于你所说的“切线”是什么意思...通过两点的线通常不是切线。您的意思是选择曲线上的一个点,然后在该点绘制切线吗?
  • this answer。它可能会有所帮助。
  • 亲爱的 Rody Oldenhuis,是的,这正是我的问题!
  • 亲爱的 petrichor,我已经写了一个类似的代码,但它没有达到我的目的。谢谢!

标签: matlab line curve


【解决方案1】:

试试下面的功能。当然,它需要进行大量调整才能应用于您的案例,但我认为这大致就是您想要的。

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

【讨论】:

  • 这帮助了我!非常感谢你! :)