create a Moving Box Simulation in 1D
7 views (last 30 days)
Show older comments
I am trying to create a simulation like this one:
And I have problems making the rectangular box moves, here is the function I wrote:
function ac_plot(~, marker, color, size)
plot(rectangle('Position',[0 0 0.2 0.2],'EdgeColor','b','LineWidth',2),...
rectangle('Position',[0 0 0.2 0.2],'EdgeColor','b','LineWidth',2),...
marker, 'Color', color, 'MarkerSize', size)
The input should be an Array of positions, I don't know how to plug it in the input of the function, and I still have to work on the function so that the box moves.
I would appreciate any help!
3 Comments
dez
on 14 Nov 2022
Do you know what the source of the gif is? I want to know the equations that were used to describe the motion.
Accepted Answer
Jan
on 11 Mar 2021
Edited: Jan
on 11 Mar 2021
axes('Xlim', [-1, 12], 'YLim', [0, 3]);
axis equal
BoxH = myBox(0, []);
dx = 0.1
for k = 1:100
pause(0.3);
myBox(dx, BoxH);
end
function BoxH = myBox(dx, BoxH)
if isempty(BoxH)
x = 1;
y = 1;
L = 1;
BoxH = gobjects(4);
BoxH(1) = line([x, x+L], [y, y], 'Color', 'b');
BoxH(2) = line([x+L, x+L], [y, y+L], 'Color', 'g');
BoxH(3) = line([x+L, x], [y+L, y+L], 'Color', 'r');
BoxH(4) = line([x, x], [y+L, y], 'Color', 'm');
else
for k = 1:4
BoxH(k).XData = BoxH(k).XData + dx;
end
end
end
More Answers (1)
Harshvardhan
on 11 Mar 2023
% Set up initial conditions
x = [0 10]; % Box starts at position 0, ends at position 10
v = 1; % Box moves at a constant velocity of 1 unit per timestep
dt = 0.1; % Timestep size
t = 0; % Start time
% Set up plot
figure;
xlim([-5 15]);
ylim([-1 1]);
xlabel('Position');
title('Moving Box Simulation');
% Main loop
while x(2) < 15 % Keep moving until the box reaches position 15
% Update position
x = x + v*dt;
% Clear plot and draw box
clf;
plot(x, [0 0], 'k-', 'LineWidth', 2);
drawnow;
pause(0.01);
% Update time
t = t + dt;
end
0 Comments
See Also
Categories
Find more on Data Exploration in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!