Clear Filters
Clear Filters

How to stop the axes from changing within loop without defining them every iteration

16 views (last 30 days)
I would like the decrease the running time of my code, setting the axes takes up a lot of time. How do a fix the axes, having then within the given limits and being equal without having to define them in every iteration of the for loop.
clc,clear variables, close all
h = 0.01;
t = 0:h:2; % Time
% Initial conditons
y0 = 2;
x0 = 5;
dydt0 = 5;
dxdt0 = 7;
Y0 = [y0 x0 dydt0 dxdt0];
% Solve system
Y = RK4_ODEs(@dYdt_ball,Y0,t);
Ysol = Y(:,1);
Xsol = Y(:,2);
% Motion plot
hf = figure(1);
for i = 1:length(Y)
plot(Xsol(i),Ysol(i),'r.',MarkerSize=30)
hold on
rectangle('Position',[-0.1 -0.1 10.2 4.9])
ht = text(4.4,5,'',Interpreter='latex');
ht.String = ['t = ' num2str(t(i),5) '\ s'];
hold off
axis equal % Slow
axis([-1 11 -1 6]) % Slow
title('Motion of Ball in Box')
pause(0.001)
end
Thank you

Accepted Answer

Voss
Voss on 17 Mar 2022
You can set up the axes once, and also create the objects in the axes once (i.e., the line representing the ball, the text for the time, and the rectangle). Then update those objects' properties as needed inside the loop. This way the axes doesn't need to change at all within the loop.
clc,clear variables, close all
h = 0.01;
t = 0:h:2; % Time
% Initial conditons
y0 = 2;
x0 = 5;
dydt0 = 5;
dxdt0 = 7;
Y0 = [y0 x0 dydt0 dxdt0];
% Solve system
Y = RK4_ODEs(@dYdt_ball,Y0,t);
Ysol = Y(:,1);
Xsol = Y(:,2);
hf = figure(1);
axis equal
axis([-1 11 -1 6])
title('Motion of Ball in Box')
ball_line = line( ...
'Parent',gca(), ...
'XData',[], ...
'YData',[], ...
'LineStyle','none', ...
'Color','r', ...
'Marker','.', ...
'MarkerSize',30);
rectangle('Position',[-0.1 -0.1 10.2 4.9]);
ht = text(4.4,5,'','Interpreter','latex');
% Motion plot
for i = 1:length(Y)
set(ball_line,'XData',Xsol(i),'YData',Ysol(i));
ht.String = ['t = ' num2str(t(i),5) '\ s'];
drawnow();
end

More Answers (1)

David Hill
David Hill on 17 Mar 2022
Why not just move it outside the loop?
hf = figure(1);
hold on
rectangle('Position',[-0.1 -0.1 10.2 4.9])
for i = 1:length(Y)
plot(Xsol(i),Ysol(i),'r.',MarkerSize=30)
ht = text(4.4,5,'',Interpreter='latex');
ht.String = ['t = ' num2str(t(i),5) '\ s'];
end
axis equal
axis([-1 11 -1 6])
title('Motion of Ball in Box')

Categories

Find more on Graphics Performance in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!