如何通过事件侦听器在 Matlab gui 中的动画行中添加数据点?

How to add datapoints in animated line in Matlab gui through an event listener?

我正在使用 GUIDE 在 Matlab 中制作一个 GUI 应用程序。我有一些轴,我在单击按钮时在其上绘制一些点。 现在我想使用动画线在同一轴上绘制线。添加到动画线的数据点来自一个事件。所以我需要在事件监听器中添加数据点。 我想知道我该怎么做,因为该事件侦听器无权访问动画线。 以下是到目前为止的代码。

单击按钮时调用此函数-

function startButton_Callback(~, ~, handles)
    x = randi(100, 20);
    y = randi(100, 20);
    plot(x, y, 'o');
    la = newClass;
    addlistener(la,'statusAnnouncement',@StatusListener);

这是事件调用的函数

function StatusListener(obj, eventData)
    h = animatedline;
    addpoints(h,eventData.coordinate(1),eventData.coordinate(2));
    drawnow

仅显示使用 plot 绘制的点。如何显示动画线? 另外,我在命令 window.

上没有收到任何错误

有几种方法可以让侦听器访问 animtedline 对象。

  1. 您可以将 StatusListener 定义为 startButton_Callback

    子函数
    function startButton_Callback(~, ~, handles)
    
        h = animatedline;
    
        la = newClass;
        addlistener(la,'statusAnnouncement',@StatusListener);
    
        %// This as a subfunction so it can "see" h
        function StatusListener(src, evnt)
            h.addpoints(evnt.coordinate(1), evnt.coordinate(2));
        end
    end
    
  2. 通过匿名函数将animtedline对象传递给回调函数

    function startButton_Callback(~, ~, handles)
        h = animatedline;
    
        la = newClass;
    
        %// Use the callback but add h as an additional input argument
        addlistener(la, 'statusAnnouncement', @(s,e)StatusListener(s,e,h))
    end
    
    %// Note the additional input argument here
    function StatusListener(obj, evnt, h)
        h.addpoints(evnt.coordinate(1), evnt.coordinate(2))
    end
    
  3. 更新animatedline里面的匿名函数

    function startButton_Callback(~, ~, handles)
        h = animatedline;
    
        la = newClass;
    
        %// Don't define a separate function and just do the update here
        addlistener(la, 'statusAnnouncement', @(s,e)h.addpoints(e.coordinate(1), e.coordinate(2)))
    end
    
  4. animatedline 对象存储在您的图 appdataguidata 中。

    function startButton_Callback(~, ~, handles)
    
        h = animatedline;
    
        %// Store the handle within the appdata of the figure
        setappdata(gcbf, 'MyAnimatedLine', h)
    
        la = newClass;
        addlistener(la,'statusAnnouncement',@StatusListener);
    end
    
    function StatusListener(obj, evnt)
        %// Get the handle from the appdata of the figure
        h = getappdata(gcbf, 'MyAnimatedLine');
        h.addpoints(evnt.coordinate(1), evnt.coordinate(2))
    end