Delay in Plotting Next Overlaid Plot When Animating 2D Plot

7 ビュー (過去 30 日間)
Cesium Modern
Cesium Modern 2025 年 2 月 26 日
コメント済み: Cesium Modern 2025 年 2 月 26 日
I have a 10 line plots that are overlaid, and I want to animate plotting each of these plots--one after the other. So I do need hold on, or some form of method to keep the previous plot as the new plot is being plotted.
The only problem I am facing is that after one plot has completed plot, before the next iteration, it takes a significant amount of time to start the next plot.
This time adds up when I have multiple overlaid plots (it compounds too).
Below I have shared my code, and a snippet of the data I am using to plot. Please point out how I can fix this
clc;clear;close all;load('data.mat');
fv=data{1};rv=data{2};
cmap = jet(5); figure;hold on
% v = VideoWriter('example', 'MPEG-4');
% open(v);
for i = 1:3
f=fv(:,i);r=rv(:,i);
color = cmap(i,:);
tic
for ii=1:length(f)
plot(f(1:ii),r(1:ii),'LineWidth',2,'Color',color);pause(0.005)
end
toc;disp('Next Plot')
end
% close(v);

採用された回答

DGM
DGM 2025 年 2 月 26 日
編集済み: DGM 2025 年 2 月 26 日
You're creating a new high-level graphics object for each plot() call. That gets very expensive, and everything will just keep getting slower. The reason for the big salient delay is that there's a large block of NaN at the end of the data. Even though nothing visible shows up, you're still creating 800+ more graphics objects during that time.
You can just trim the NaNs out and update the one object for each series.
load('data.mat');
fv = data{1};
rv = data{2};
cmap = jet(5);
nseries = size(fv,2);
hp = gobjects(nseries,1);
for i = 1:nseries
f = fv(:,i);
r = rv(:,i);
color = cmap(i,:);
% a large chunk (~74%) of the data is invalid/blank
% consider omitting that chunk to save time
mk = ~isnan(f);
f = f(mk);
r = r(mk);
% instead of creating 1200 overlapping line objects of increasing length,
% just create one and update it
for ii = 1:length(f)
if ii == 1
hp(i) = plot(f(1:ii),r(1:ii),'LineWidth',2,'Color',color);
hold on
else
hp(i).XData = f(1:ii);
hp(i).YData = r(1:ii);
end
pause(0.005)
end
disp('Next Plot')
end
There may be a drawback to just omitting all NaNs. If there are scattered blocks of NaN in the middle of the data which should properly show up as gaps, omitting them will cause a line to be connected across the gap. At a glance, it looks like all the NaNs are concentrated in a block at the end, but you might want to make sure that everything is still okay. More care may need to be taken to actually isolate the trailing block alone.
  1 件のコメント
Cesium Modern
Cesium Modern 2025 年 2 月 26 日
Thanks, this works as I wanted it to! Appreciate the detailed answer.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File Exchange2-D and 3-D Plots についてさらに検索

製品


リリース

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by