How can I fix the previous plot as background, and then make a newplot that updating with a loop?

2 次查看(过去 30 天)
I wonder if there can be a method that fix the previous plot as background, and I have a code to generate the background:
P=repmat((-10:10)',1,21);
Q=repmat(-10:10,21,1);
p_e_x=sqrt(3)*P(:)*cos(pi/6)+sqrt(3)*Q(:)*cos(pi/6);
p_e_y=sqrt(3)*P(:)*sin(pi/6)-sqrt(3)*Q(:)*sin(pi/6);
p_m_x=p_e_x+1;
p_m_y=p_e_y;
figure(1)
r=[1,sqrt(3),2,sqrt(3),1];
theta=pi/6*(0:4);
for i=1:length(p_e_x)
p_grp=p_e_x(i)+1i*p_e_y(i)+r.*exp(1i*theta);
p_grp=[p_e_x(i)+1i*p_e_y(i),p_grp,p_e_x(i)+1i*p_e_y(i)];
plot(p_grp,'-');hold on
end
This is the code for drawing a hexagonal background. Then I want to make newplot on this figure, but the newplot will be different in a loop:
for t=1:length(time)
% plot something new as t changed
end
I don't want to overlap the newplots of each moment together. I just want a single newplot in a t with the background plotted.
Is there any good way to implement it?

采纳的回答

Ruchika Parag
Ruchika Parag 2024-11-27
Hi @剑豪 戴, to achieve a plot where the background is fixed and new plots are updated without overlapping, you can use the 'cla' (clear axes) function to clear the current plot while keeping the background intact. Here's how you can modify your code to accomplish this:
  1. Plot the background once and hold it.
  2. Use a loop to update the new plot for each time step, clearing only the new data.
Here's a modified version of your code:
P = repmat((-10:10)', 1, 21);
Q = repmat(-10:10, 21, 1);
p_e_x = sqrt(3) * P(:) * cos(pi/6) + sqrt(3) * Q(:) * cos(pi/6);
p_e_y = sqrt(3) * P(:) * sin(pi/6) - sqrt(3) * Q(:) * sin(pi/6);
figure(1);
r = [1, sqrt(3), 2, sqrt(3), 1];
theta = pi/6 * (0:4);
hold on;
for i = 1:length(p_e_x)
p_grp = p_e_x(i) + 1i * p_e_y(i) + r .* exp(1i * theta);
p_grp = [p_e_x(i) + 1i * p_e_y(i), p_grp, p_e_x(i) + 1i * p_e_y(i)];
plot(p_grp, '-');
end
time = 1:10;
for t = 1:length(time)
cla;
for i = 1:length(p_e_x)
p_grp = p_e_x(i) + 1i * p_e_y(i) + r .* exp(1i * theta);
p_grp = [p_e_x(i) + 1i * p_e_y(i), p_grp, p_e_x(i) + 1i * p_e_y(i)];
plot(p_grp, '-');
end
new_x = cos(t);
new_y = sin(t);
plot(new_x, new_y, 'ro', 'MarkerSize', 8, 'MarkerFaceColor', 'r');
pause(0.5);
end
Hope this helps!

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Simulink 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by