use*_*045 1 performance profiler matlab animation drawnow
我正在尝试创建一个动画情节,但是我的代码非常慢,也许我使用的方法太幼稚了。在下面的示例中,我有4个子图,每个子图有3行,并在“时间”循环中进行了更新。
clc;clear;close all;
state = {'$x-Position$','$x-Velocity$','$y-Position$','$y-Velocity$'};
ylabels = {'$x$','$\dot{x}$','$y$','$\dot{y}$'};
options1 = {'interpreter','latex'};
options2 = {'interpreter','latex','fontsize',20};
maxT = 300;
for pp = 1:4
hh1(pp)=subplot(2,2,pp);
xlabel('$t$',options2{:});
ylabel(ylabels{pp},options2{:});
title(state{pp},options1{:})
xlim([0 maxT])
hold on
end
x = randn(4,300);
z = randn(4,300);
x_est = randn(4,300);
for k = 2:maxT
for p = 1:4
plot(hh1(p),k-1:k,x(p,k-1:k),'b','linewidth',2)
plot(hh1(p),k-1:k,z(p,k-1:k),'m')
plot(hh1(p),k-1:k,x_est(p,k-1:k),':k','linewidth',2)
end
drawnow;
end
Run Code Online (Sandbox Code Playgroud)
从探查器输出中可以看出,这drawnow正在浪费时间。有什么方法可以使我更有效地创建此动画?
因为您需要动画,所以没有替代方法drawnow来更新框架。但是,并不是drawnow特别让您放慢速度-探查器可能会产生误导作用... drawnow仅更新自上次重新绘制以来的所有图形更改(在您的情况下为十几个新图)!
您会发现这hold非常慢。例如,如果您比较明智地持有商品,请删除现有商品hold on,仅在实际绘图时才拥有商品
% ... above code the same but without 'hold on'
for p = 1:4
hold(hh1(p), 'on');
% plots
hold(hh1(p), 'off');
end
Run Code Online (Sandbox Code Playgroud)
这样可以在我的PC上节省约10%的时间(从12.3秒降低到11.3秒)。
真正的加速来自hold完全删除以及所有单个plot呼叫!此方法也不会影响行格式,这将有助于提高速度。在此处查看有关更新绘图数据的先前问题。
只需更新绘图数据,而不添加绘图即可。这使我的速度提高了约68%(从12.3秒降低到4.0秒)。
% ... your same setup
% Initialise plot data
x = randn(4,300);
z = randn(4,300);
x_est = randn(4,300);
plts = cell(4,3);
hh1 = cell(4,1);
% Loop over subplots and initialise plot lines
for p = 1:4
hh1{p}=subplot(2,2,p);
xlabel('$t$',options2{:});
ylabel(ylabels{p},options2{:});
title(state{p},options1{:})
xlim([0 maxT])
% Hold on to make 3 plots. Create initial points and set line styles.
% Store the plots in a cell array for later reference.
hold on
plts{p,1} = plot(hh1{p},1:2,x(p,1:2),'b','linewidth',2);
plts{p,2} = plot(hh1{p},1:2,z(p,1:2),'m');
plts{p,3} = plot(hh1{p},1:2,x_est(p,1:2),':k','linewidth',2);
hold off
end
% March through time. No replotting required, just update XData and YData
for k = 2:maxT
for p = 1:4
set(plts{p,1}, 'XData', 1:k, 'YData', x(p,1:k) );
set(plts{p,2}, 'XData', 1:k, 'YData', z(p,1:k) );
set(plts{p,3}, 'XData', 1:k, 'YData', x_est(p,1:k) );
end
drawnow;
end
Run Code Online (Sandbox Code Playgroud)
现在,绘图已相当优化。如果要使动画更快,则只需使用第2、3,...,n个时间步(而不是每个时间步)进行绘制即可for k = 2:n:maxT。