Live Script: Multiple Figures Merge into a Single Animation

18 views (last 30 days)
When running a Live Script that plots several figures inside a loop, I expect MATLAB to produce separate animations, one per figure.
However, all plots are combined into a single inline animation — the frames from different figures appear alternately, making the animation look like a “blinking” mix of results.
Here’s a simplified version of my code:
a = linspace(0, pi ,100);
for ii = 1:100
figure(1); hold on; box on
plot(gca, a(ii), sin(a(ii)), 'r*')
xlim([0 pi]); ylim([-1 1]);
drawnow
figure(2); hold on; box on
plot(gca, a(ii), cos(a(ii)), 'r*')
xlim([0 pi]); ylim([-1 1]);
drawnow
end
In the Live Editor, instead of getting two separate animations (one for figure(1) and one for figure(2)), the frames from both are merged into one.
Any guidance or best practices for managing multiple animated figures in Live Scripts would be appreciated.

Answers (1)

Dyuman Joshi
Dyuman Joshi on 14 Oct 2025 at 14:59
Here's an approach with animatedline and subplot -
%Data
N = 500;
x = linspace(0, pi, N);
y1 = sin(x);
y2 = cos(x);
%Generate subplot
sub = subplot(2,1,1);
axis([0,2*pi,-1,1])
h1=animatedline('Color','r');
subplot(2,1,2)
axis([0,2*pi,-1,1])
h2=animatedline('Color','k');
%Plot lines point by point
for k=1:N
addpoints(h1,x(k),y1(k));
addpoints(h2,x(k),y2(k));
drawnow
end

Categories

Find more on Animation in Help Center and File Exchange

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!