Search code examples
matlabmatlab-figurefill

Matlab: Why is the fill function not filling the area between two circles?


I'm trying to fill the intersecting area between two circles in Matlab. I've quite literally copied and pasted this piece of code from this article on Matlab Central.

t = linspace(0, 2*pi, 100);
cir = @(r,ctr) [r*cos(t)+ctr(1); r*sin(t)+ctr(2)]; % Circle Function
c1 = cir(1.0, [0; 0]);
c2 = cir(1.5, [1; 1]);
in1 = find(inpolygon(c1(1,:), c1(2,:), c2(1,:), c2(2,:))); % Circle #1 Points Inside Circle #2
in2 = find(inpolygon(c2(1,:), c2(2,:), c1(1,:), c1(2,:))); % Circle #2 Points Inside Circle #1
[fillx,ix] = sort([c1(1,in1) c2(1,in2)]); % Sort Points
filly = [c1(2,in1) (c2(2,in2))];
filly = filly(ix);
figure(1)
plot(c1(1,:), c1(2,:))
hold on
plot(c2(1,:), c2(2,:))
fill([fillx fliplr(fillx)], [filly fliplr(filly)], 'g', 'EdgeColor','none')
hold off
axis square

What I end up with is the following image:

enter image description here

However, it should appear as this image:

enter image description here

Why is the area not being filled as it is in the example article?


Solution

  • If you have Mapping Toolbox you can use polybool to find the intersection between to polygones, and than patch (which dosen't require Mapping Toolbox, and is better than fill) to draw it. The folowing code works even without the first 2 lines that use poly2cw, but it issues some warnings. This can be solved with the poly2cw trasfomation:

    [c1(1,:), c1(2,:)] = poly2cw(c1(1,:), c1(2,:)); % clock-wise transform
    [c2(1,:), c2(2,:)] = poly2cw(c2(1,:), c2(2,:)); % clock-wise transform   
    [xb, yb] = polybool('intersection',c1(1,:),c1(2,:),c2(1,:), c2(2,:));
    plot(c1(1,:), c1(2,:))
    hold on
    plot(c2(1,:), c2(2,:))
    patch(xb, yb, 1, 'FaceColor', 'g','EdgeColor','none')
    axis equal
    

    circle intersection