MATLAB Answers

# Loop imagesc together for traffic simulation

2 views (last 30 days)
Anthony Purcell on 25 Mar 2021
Answered: Pavan Guntha on 30 Mar 2021
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
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Answers (1)

Pavan Guntha on 30 Mar 2021
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!
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!