MATLAB: Can you make the output of this graph have multiple colors, like one timing bit is one color and the next one is another color.

color of plot linescolor varies within a single plot linevarying line color

h = [1 1 0 1 0 1 0 1];
bitrate = 1;
n = 1000;
T = length(h)/bitrate;
N = n*length(h);
dt = T/N;
t = 0:dt:T;
x = zeros(1,length(t));
lastbit = 1;
for i=1:length(h)
if h(i)==1
x((i-1)*n+1:i*n) = -lastbit;
lastbit = -lastbit;
else x((i-1)*n+1:i*n) = lastbit;
end
end
d=plot(t,x);grid on;
title('Line code POLAR NRZ-I');
set(d,'LineWidth',2.5);
axis([0 length(h) -1.5 1.5]);
counter = 0;
lastbit = 1;
for i = 1:length(t)
if t(i)>counter
counter = counter + 1;
if x(i)~=lastbit
result(counter) = 1;
lastbit = -lastbit;
else result(counter) = 0;
end
end
end
disp(result);

Best Answer

To plot in different colors you have to specify a linespec in plot, like
d=plot(t,x, 'r-', 'LineWidth', 2); % Plot red line of width 2.
d=plot(t,x, 'b-', 'LineWidth', 3); % Plot blue line of width 3.
d=plot(t,x, '-', 'LineWidth', 2); % Plot line of width 2 in next default color;
Here's a full demo:
numLines = 10
lineColors = jet(numLines);
x = linspace(0, 2*pi, 1000);
period = pi;
legendStrings = cell(numLines, 1);
for k = 1 : numLines
y = sin(2*pi*x/(k * period));
plot(x, y, '-', 'Color', lineColors(k, :), 'LineWidth', 3);
hold on;
legendStrings{k} = sprintf('Curve #%d', k);
end
grid on;
xlabel('x', 'FontSize', 20);
ylabel('y', 'FontSize', 20);
legend(legendStrings, 'Location', 'southwest');
Also see attached m-file for a different demo.