1

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

4

1 回答 1

6

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

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
于 2012-11-26T12:00:21.380 回答