首页 > 解决方案 > 如何从 Matlab 中的数据提示光标中提取任意数量的数据点?

问题描述

我正在尝试显示一系列图形(在下面的示例代码中,2 个图形),这样我将一个接一个地浏览每个图形并单击一些点并从光标输出点的 (x,y) 位置. 根据一些在线帮助,我使用该pause函数,单击一个点,按下一个键,使用datacursormodegetCursorInfo函数将(x,y)数据输出到 Matlab 终端,然后单击下一个点。我不知道我要在每个图中选择多少个点,但假设它会小于 10。因此,我使用了一个for循环(for rc1=1:10),其中包含一个暂停语句。问题是当我完成较少的点数时,我不知道如何退出这个循环(让我们说rc1=5) 并移至下一个图。我该怎么做呢 ?如果代码可以表明我已经完成了从当前图形中选择点并让我跳出循环(例如,应该工作rc1=1:10的某种if (condition) continue语句)。if isfield ... end

clc
clearvars
close all

for rc2=1:2
    
    figure;
    
    x = linspace(0,10,150);
    y = cos(5*x);
    fig = gcf;
    plot(x,y)
    % Enable data cursor mode
    datacursormode on
    dcm_obj = datacursormode(fig);
    % Set update function
    set(dcm_obj,'UpdateFcn',@myupdatefcn)
    % Wait while the user to click
    disp('Click line to display a data tip, then press "Return"');
    
    for rc1=1:10
        pause
        % Export cursor to workspace
        info_struct = getCursorInfo(dcm_obj);
        if isfield(info_struct, 'Position')
            fprintf('%.2f %.2f \n',info_struct.Position);
        end
        
     end
    
end

function output_txt = myupdatefcn(~,event_obj)
% ~            Currently not used (empty)
% event_obj    Object containing event data structure
% output_txt   Data cursor text
pos = get(event_obj, 'Position');
output_txt = {['x: ' num2str(pos(1))], ['y: ' num2str(pos(2))]};
end

标签: matlabpause

解决方案


好的,我想通了。在内部循环中添加一个try, catch, break, end序列并将该pause, getCursorInfo, isfield段放在该try部分中使其工作。现在我选择几个点,只需关闭当前图形,按一个键并移动到下一个图形。这行得通。

clc
clearvars
close all

for rc2=1:2
    
    figure;
    
    x = linspace(0,10,150);
    y = cos(5*x);
    fig = gcf;
    plot(x,y)
    % Enable data cursor mode
    datacursormode on
    dcm_obj = datacursormode(fig);
    % Set update function
    set(dcm_obj,'UpdateFcn',@myupdatefcn)
    % Wait while the user to click
    disp('Click line to display a data tip, then press "Return"');
    
    for rc1=1:10
        % Export cursor to workspace
        try
            pause
            info_struct = getCursorInfo(dcm_obj);
            if isfield(info_struct, 'Position')
                fprintf('%.2f %.2f \n',info_struct.Position);
            end
        catch
            break;
        end
     end
    
end

function output_txt = myupdatefcn(~,event_obj)
% ~            Currently not used (empty)
% event_obj    Object containing event data structure
% output_txt   Data cursor text
pos = get(event_obj, 'Position');
output_txt = {['x: ' num2str(pos(1))], ['y: ' num2str(pos(2))]};
end

推荐阅读