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

조회 수: 11 (최근 30일)
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

채택된 답변

Voss
Voss 2022년 3월 17일
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

추가 답변 (1개)

David Hill
David Hill 2022년 3월 17일
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')

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by