create a Moving Box Simulation in 1D

7 visualizzazioni (ultimi 30 giorni)
Hidd_1
Hidd_1 il 11 Mar 2021
Risposto: Harshvardhan il 11 Mar 2023
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 Commenti
Hidd_1
Hidd_1 il 11 Mar 2021
Modificato: Hidd_1 il 11 Mar 2021
I saved the positions of the box in an array called q_Matrix, I don't know how to plug it in the input of the function, and I still have to find a way to make the box moves.
It would be great if you know how to create a colorful box like the one in the simulation.
dez
dez il 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.

Accedi per commentare.

Risposta accettata

Jan
Jan il 11 Mar 2021
Modificato: Jan il 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
  1 Commento
Hidd_1
Hidd_1 il 11 Mar 2021
Modificato: Hidd_1 il 11 Mar 2021
It really works!! Thank you

Accedi per commentare.

Più risposte (1)

Harshvardhan
Harshvardhan il 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

Categorie

Scopri di più su Data Exploration in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by