将下面的函数保存到路径上名为 addPoint.m 的 m 文件中,然后在命令行中输入以下内容:
>> hFigure = 图;
>> hAxes = axes('父', hFigure);
>> set(hAxes, 'ButtonDownFcn', @addPoint);
这将创建一个坐标区,每次单击坐标区时都会执行 addPoint。 addPoint 如果不存在线,则创建一条线,获取单击点的坐标并将这些坐标添加到线的XData 和YData 属性中。
function addPoint(hObject, eventdata)
% Get the clicked point.
currentPoint = get(hObject, 'CurrentPoint');
% Get the handle to the plotted line. Create a line if one doesn't exist
% yet.
hLine = get(hObject, 'Children');
if isempty(hLine)
hLine = line(0, 0, ...
'Parent', hObject, ...
'Marker', 's', ...
'MarkerEdgeColor', 'r');
end
% Temporarily set the axes units to normalized.
axesUnits = get(hObject, 'Units');
set(hObject, 'Units', 'normalized');
% Get the clicked point and add it to the plotted line.
data(:,1) = get(hLine, 'XData');
data(:,2) = get(hLine, 'YData');
data(end+1,:) = [currentPoint(1,1) currentPoint(1,2)];
data = sortrows(data, 1);
set(hLine, 'XData', data(:,1), 'YData', data(:,2));
% Reset the axes units.
set(hObject, 'Units', axesUnits);
您可以通过防止在第一次点击后自动更新坐标区限制来改善这一点。