function fillline(x, y1, y2, col1, col2)
if nargin < 3
x = -10:10;
y1 = sin(x);
y2 = cos(x);
end
if nargin < 5
col1 = [1 0 0];
col2 = [0 0 1];
end
hold on
colpatch(y1 >= y2, col1, x, y1, y2)
colpatch(y2 >= y1, col2, x, y1, y2)
plot(x, y1, '-', 'Color', col1)
plot(x, y2, '-', 'Color', col2)
hold off
function colpatch(ind, col, x, y1, y2)
if ~any(ind)
return
end
col = lighten(col);
x = x(:)'; y1 = y1(:)'; y2 = y2(:)'; ind = ind(:)';
if all(ind)
fill([x x(end) fliplr(x) x(1)], ...
[y1 y1(end) fliplr(y2) y2(1)], col, 'EdgeColor', col);
return
end
val = cumsum(diff([0 ind]) == 1).*ind;
v = 1;
ind = find(val == v);
while ~isempty(ind)
xi = x(ind); y1i = y1(ind); y2i = y2(ind);
ii = ind(1);
if ii > 1
line1 = [x(ii) y1(ii); x(ii-1) y1(ii-1)];
line2 = [x(ii) y2(ii); x(ii-1) y2(ii-1)];
[xis_left yis_left] = lineintercept(line1, line2);
else
xis_left = [];
yis_left = [];
end
ii = ind(end);
if ii < numel(x)
line1 = [x(ii) y1(ii); x(ii+1) y1(ii+1)];
line2 = [x(ii) y2(ii); x(ii+1) y2(ii+1)];
[xis_right yis_right] = lineintercept(line1, line2);
else
xis_right = [];
yis_right = [];
end
fill([xis_left xi xis_right fliplr(xi)], ...
[yis_left y1i yis_right fliplr(y2i)], col, 'EdgeColor', col);
v = v + 1;
ind = find(val == v);
end
function [xis yis] = lineintercept(line1, line2)
slope = @(line) (line(2,2) - line(1,2))/(line(2,1) - line(1,1));
m1 = slope(line1);
m2 = slope(line2);
intercept = @(line,m) line(1,2) - m*line(1,1);
b1 = intercept(line1,m1);
b2 = intercept(line2,m2);
xis = (b2-b1)/(m1-m2);
yis = m1*xis + b1;
function col = lighten(col)
col = col + 0.8*([1 1 1] - col);
Best Answer