# Matlab : color code portion of the line

I have the following array that contains ALL of my points:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

y = [1,9,8,5,2,8,1,4,3,11,13,15,16,13,12];

I plot my blue line with the following command:

plot(x,y, 'blue');

I want to color code sections of the generated plot.

Example:

x1 = [2,3,4,11,12,13];

numbers in x range of x1 should be red on the x axis on the original plot.

Looking at this post , it is recommended by the author to draw out different lines, based on some qualifying boolean.

Hence, I have updated my code to be as follows:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
y = [1,9,8,5,2,8,1,4,3,11,13,15,16,13,12];
x1 = [2,3,4,11,12,13];

canPlot = ismember(x, x1);
hold on;
plot(x,y, 'blue');
plot(x(canPlot), y(canPlot), 'red');
hold off;

However, the generated graph connects "disconnected" points. Here is a photo of the problem:

As you can see above, the two segments x1 when it equates to 4 and x1 when it equates to 11 are connected. I don't want them to be connected. How can I get rid of that connecting line without splitting x1 into to sequential variables?

I.e

These points should be connected to formulate a red line:

2,3,4

11,12,13

These points should not be connected to formulate a red line:

4,11

You can use NaN as a delimiter between the sequential values in your vector to plot, and then plot divide it into seperated lines.

I don't know about a comfort way in Matlab to append and add values in the middle of a vector, so I'll create a new vector of NaN's and then will copy the desired values to the matching indices:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
y = [1,9,8,5,2,8,1,4,3,11,13,15,16,13,12];
x1 = [2,3,4,11,12,13];

xPlot=nan(1,length(x1)+sum(diff(x1)>1));
xPlot((1:length(x1))+[0 cumsum(diff(x1)>1)])=x(ismember(x,x1));
yPlot=nan(1,length(x1)+sum(diff(x1)>1));
yPlot((1:length(x1))+[0 cumsum(diff(x1)>1)])=y(ismember(x,x1));
figure; plot(x,y,'b')
hold on; plot(xPlot,yPlot,'r')