我需要在特定点绘制曲线的切线(比如用户选择该点)。我编写了一个代码,允许用户手动拾取两个点,然后在它们之间绘制一条线。但我想自动化这个过程。有人可以建议任何算法/已经实现的matlab代码吗?
答案 0 :(得分: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