I've to draw the status of a traffic ligthers, as in the figure, i've to plot a red line if the light is red or a green one if it is green.

1 次查看(过去 30 天)
someone can help me??

回答(1 个)

Jacob Mathew
Jacob Mathew 2024-2-19
Going through the question, I understand that you want to plot a line that alternates between red and green corresponding to the change in color of the traffic light.
We can achieve this behaviour by plotting the individual lines representing one state of the traffic signal and then by using hold on we can continue plotting the rest of the traffic signal states.
Consider the example below:
function test
% Simulating two traffic lights switching between red and green
trafficAlgorithm1 = struct( ...
'signalPosition',100, ...
'startTime',[0,20,25,45,50], ...
'stopTime',[20,25,45,50,70], ...
'color',["red","green","red","green","red"]);
trafficAlgorithm2 = struct( ...
'signalPosition',200, ...
'startTime',[0,20,25,45,50], ...
'stopTime',[20,25,45,50,70], ...
'color',["green","red","green","red","green"]);
% Plotting the simulation
hold on
ylim([0 300])
for index = 1:length(trafficAlgorithm1.startTime)
trafficPlot(trafficAlgorithm1.signalPosition, ...
trafficAlgorithm1.startTime(index) ...
,trafficAlgorithm1.stopTime(index), ...
trafficAlgorithm1.color(index));
trafficPlot(trafficAlgorithm2.signalPosition, ...
trafficAlgorithm2.startTime(index), ...
trafficAlgorithm2.stopTime(index), ...
trafficAlgorithm2.color(index));
end
end
function trafficPlot(signalPosition, start, stop, color)
if strcmpi(color,"red")
% Plotting the red state of traffic signal
plot([start, stop], ...
[signalPosition,signalPosition], ...
'r-','LineWidth',2);
elseif strcmpi(color,"green")
% Plotting the green state of traffic signal
plot([start, stop], ...
[signalPosition,signalPosition], ...
'g-','LineWidth',2);
else
disp("ERROR: Invalid color")
end
end
The test function is initialising a simulated traffic signal value. It contains the traffic signal position, which determines the y axis value of the line being plotted, the startTime and stopTime determines the x axis value. The color determines whether the line we are plotting should be red or green, corresponding to the state of the traffic signal.
We then plot this using the trafficPlot function that is iteratively called within the test function.
The output of the above is as follows:
Output of running the test function
However, without knowing how the traffic signals are generated or what algorithm is used to determine how long it takes between switching, the acutal implementation can vary from the example above. To customise the code to suit your needs, you can refer to the following documentation of plot function:

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by