【问题标题】:How to remove the track of a N point matlab animation [duplicate]如何去除N点matlab动画的轨迹[重复]
【发布时间】:2016-08-17 18:32:20
【问题描述】:

我已经在 1D 中为 N 个点的运动设置了动画。问题是我无法找到摆脱之前的情节并移除运动中创建的轨迹的方法。

function sol=Draw(N)
    %N is the number of points
    PointsPos=1:N
    for s=1:1000
        for i=1:N
            PointsPos(i)=PointsPos(i)+ rand(1,1)
            %The position of the point is increased.
        end
        for i=1:N
            %loop to draw the points after changing their positions
            hold on
            plot(PointsPos,1,'.')
        end
        pause(0.005) 
        %here I want to delete the plots of the previous frame s
    end     
    end

【问题讨论】:

    标签: matlab animation plot matlab-figure


    【解决方案1】:

    MATLAB 程序动画的一般准则是:

    尽可能避免在动画循环中创建或删除图形对象。

    因此,如果您在动画循环中调用 plot image surfdelete,那么您很可能没有以最佳方式执行。

    这里,最佳做法是在动画循环之前创建绘图,然后使用 set(plot_handle, 'XData', ...) 更新绘图点的 x 坐标。

    您还应该将 rand(1, N) 添加到 PointsPos,而不是添加 rand(1, 1) N 次。

    所以你的代码应该看起来有点类似于下面:

    function sol=Draw(N)
        PointsPos=1:N
        h = plot(PointsPos, ones(1, N), '.');
        for s=1:1000
            PointsPos=PointsPos+ rand(1,N)
            set(h, 'XData', PointsPos);
    
            pause(0.005) 
        end
    end 
    

    【讨论】:

    • 如果你想把它看成动画,你应该把暂停放在循环中
    • @EBH 感谢您指出这一点。我直接在 OP 的代码上编辑并删除了错误的“结束”。现已更正。
    【解决方案2】:

    如果我理解您的目标,那么这应该可以满足您的要求:

    function sol = Draw(N)
    steps = 1000;
    % N is the number of points
    PointsPos = cumsum([1:N; rand(steps-1,N)],1);
    p = scatter(PointsPos(1,:),ones(N,1),[],(1:N).');
    colormap lines
    for s = 2:steps
        p.XData = PointsPos(s,:);
        drawnow
    end
    end
    

    注意:

    1. 循环内无需计算任何内容,使用矢量化和cumsum 一次性计算所有点的位置(即所有PointsPos 矩阵)。
    2. 对于绘制不相关的圆圈,scatter 会是更好的选择。
    3. 您可以使用drawnow 来更新您的绘图,而不是在任意时间使用pause

    【讨论】:

      猜你喜欢
      • 2013-05-10
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      相关资源
      最近更新 更多