Matlab update plot with multiple data lines/curves

倾然丶 夕夏残阳落幕 提交于 2019-11-28 05:23:05

问题


I want to update a plot with multiple data lines/curves as fast as possible. I have seen some method for updating the plot like using:

h = plot(x,y);
set(h,'YDataSource','y')
set(h,'XDataSource','x')
refreshdata(h,'caller');

or

set(h,'XData',x,'YData',y);

For a single curve it works great, however I want to update not only one but multiple data curves. How can I do this?


回答1:


If you create multiple plot objects with a single plot command, the handle returned by plot is actually an array of plot objects (one for each plot).

plots = plot(rand(2));
size(plots)

    1   2

Because of this, you cannot simply assign another [2x2] matrix to the XData.

set(plots, 'XData', rand(2))

You could pass a cell array of new XData to the plots via the following syntax. This is only really convenient if you already have your new values in a cell array.

set(plots, {'XData'}, {rand(1,2); rand(1,2)})

The other options is to update each plot object individually with the new values. As far as doing this quickly, there really isn't much of a performance hit by not setting them all at once, because they will not actually be rendered until MATLAB is idle or you explicitly call drawnow.

X = rand(2);
Y = rand(2);

for k = 1:numel(plots)
    set(plots(k), 'XData', X(k,:), 'YData', Y(k,:))
end

% Force the rendering *after* you update all data
drawnow

If you really want to use the XDataSource and YDataSource method that you have shown, you can actually do this, but you would need to specify a unique data source for each plot object.

% Do this when you create the plots
for k = 1:numel(plots)
    set(plots(k), 'XDataSource', sprintf('X(%d,:)', k), ...
                  'YDataSource', sprintf('Y(%d,:)', k))
end

% Now update the plot data
X = rand(2);
Y = rand(2);

refreshdata(plots)



回答2:


You can use drawnow:

%Creation of the vectors

x = 1:100;
y = rand(1,100);

%1st plot 
h = plot(x,y);

pause(2);

%update y
y = rand(1,100);
set(h,'YData',y)
%update the plot.
drawnow


来源:https://stackoverflow.com/questions/36155000/matlab-update-plot-with-multiple-data-lines-curves

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!