필터 지우기
필터 지우기

Loop imagesc together for traffic simulation

조회 수: 6 (최근 30일)
Anthony Purcell
Anthony Purcell 2021년 3월 25일
답변: Pavan Guntha 2021년 3월 30일
So i have a school assignment that is asking us to make a road with 2 cars traveling in opposite directions using imagesc. My issue is I cannot get the loop to show both cars at once as when one car gets plotted the other gets deleted. I know there are specific matlab programs to make road simulations but we can't use that. My code is this
rw = 11;
rl = 40;
road = zeros(rw,rl);
road2= zeros(rw,rl);
xpos = 1;
ypos = 3;
xpos2= 39;
ypos2= 7;
road(ypos,xpos) = 1;
road2(ypos2,xpos2)=1;
imagesc(road)
axis equal
for t = 0 : 5
road(ypos,xpos) = 0;
xpos = xpos + 1;
road(ypos,xpos) = 1;
imagesc(road); hold on
t1 = sprintf('time = %f sec' , t);
title(t1);
axis equal
pause(0.5)
road2(ypos2,xpos2)=0;
xpos2 = xpos2 - 1; hold on
road2(ypos2,xpos2)=1;
imagesc(road2)
t1 = sprintf('time = %f sec' , t);
title(t1);
axis equal
pause(0.5)
end

답변 (1개)

Pavan Guntha
Pavan Guntha 2021년 3월 30일
Hi Anthony,
You could look at the following code:
rw = 11;
rl = 40;
road = zeros(rw,rl);
xpos1 = 1;
ypos1 = 3;
xpos2 = 39;
ypos2 = 7;
road(ypos1, xpos1) = 1;
figure(1);
clf;
imagesc(road)
axis equal
hold on
for t = 0 : 20
road(ypos1,xpos1) = 0;
xpos1 = xpos1 + 1;
road(ypos1,xpos1) = 1;
imagesc(road);
t1 = sprintf('time = %f sec' , t);
title(t1);
pause(0.1)
road(ypos2,xpos2) = 0;
xpos2 = xpos2 - 1;
road(ypos2,xpos2) = 1;
imagesc(road)
pause(0.1)
end
Calling imagesc within a loop refreshes the figure window even if you put "hold on" in your case because you have considered two roads, one each for the 2 cars. Instead you can consider a single road and appropriately vary the positions of car1 and car2 as shown in the previous code.
Hope this helps!

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by