create a Moving Box Simulation in 1D

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 件のコメント

Jan
Jan 2021 年 3 月 11 日
The question is not clear yet. You show some code, but do not explain, what you want to do in the next step. Why is the first input of your function ignored?
rectangle is a matlab command, which draws a rectangle. You cannot insert in inside a plot command. What do you want to achieve?
Hidd_1
Hidd_1 2021 年 3 月 11 日
編集済み: Hidd_1 2021 年 3 月 11 日
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 2022 年 11 月 14 日
Do you know what the source of the gif is? I want to know the equations that were used to describe the motion.

サインインしてコメントする。

 採用された回答

Jan
Jan 2021 年 3 月 11 日
編集済み: Jan 2021 年 3 月 11 日

1 投票

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 件のコメント

Hidd_1
Hidd_1 2021 年 3 月 11 日
編集済み: Hidd_1 2021 年 3 月 11 日
It really works!! Thank you

サインインしてコメントする。

その他の回答 (1 件)

Harshvardhan
Harshvardhan 2023 年 3 月 11 日

0 投票

% 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

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

質問済み:

2021 年 3 月 11 日

回答済み:

2023 年 3 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by