MATLAB: Shade area between two line that changes color when two line cross

colorshade

How can i change the color of the area between two lines plotted when one of them cross over the last one?
Example
Goal: when the red line is over the blue line area must be yellow
when the blue line is over the red line area must be green
x=[1,2,3,4,5,6,7,8,9,11,12,13,14,15,17,18,19];
y=[2,3,4,1,1,0,0,9,15,16,20,-3,-5,-6,10,11,12];
y1=[-2,-3,-4,-1,-1,0,0,-9,-15,-16,-20,3,5,6,-10,-11,-12];
n=length(x);
figure(1);
plot(x,y,'r-','LineWidth',3);
hold on;
plot(x,y1,'b-','LineWidth',3);
for i=1:n
if y1(i)-y(i)>0
fill([x,fliplr(x)],[y,fliplr(y1)],'g');
end
if y1(i)-y(i)<0
fill([x,fliplr(x)],[y,fliplr(y1)],'y');
end
end
hold off;

Best Answer

Try this:
x=[1,2,3,4,5,6,7,8,9,11,12,13,14,15,17,18,19];
y=[2,3,4,1,1,0,0,9,15,16,20,-3,-5,-6,10,11,12];
y1=[-2,-3,-4,-1,-1,0,0,-9,-15,-16,-20,3,5,6,-10,-11,-12];
n=length(x);
figure(1);
plot(x,y,'r-','LineWidth',3);
hold on;
plot(x,y1,'b-','LineWidth',3);
Lv = (y1 - y) > 0; % Logical Vector
Lvseg = find(diff([Lv(1) +Lv])); % Crossing Points
patch([x(~Lv(1:Lvseg(1))) fliplr(x(~Lv(1:Lvseg(1))))], [y(~Lv(1:Lvseg(1))) fliplr(y1(~Lv(1:Lvseg(1))))], 'y') % Beginning To First Crossing Point
patch([x(~Lv(Lvseg(2):end)) fliplr(x(~Lv(Lvseg(2):end)))], [y(~Lv(Lvseg(2):end)) fliplr(y1(~Lv(Lvseg(2):end)))], 'y') % Second crossing Point To End
patch([x(Lv) fliplr(x(Lv))], [y(Lv) fliplr(y1(Lv))], 'g')
hold off
producing:
shade area between two line that changes color when two line cross - 2019 12 16.png
The unfilled gaps are due to the resolutions of the vectors. To fill them, use the linspace and interp1 functions to increase the resolutions of all the vectors.