MATLAB Answers

Filling areas between curves

1 view (last 30 days)
Michael Thomas
Michael Thomas on 19 Feb 2020
Answered: darova on 19 Feb 2020
I'm relatively inexperienced with MATLAB and I'm having a hard time understanding using patch or fill. I would like to shade each of the four areas generated by the intersection of these two curves.
Here's my code:
load 'twopar2gga.dat'
x = twopar2gga;
x1 = x(4001:4137,1);
y1 = x(4001:4137,2);
x2 = x(4138:4201,1);
y2 = x(4138:4201,2);
hold on
axis([0 1 0 1])
If someone could expain how to do this that'd be amazing. I've attached my data.
Michael Thomas
Michael Thomas on 19 Feb 2020
I didn't, but I do now

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 19 Feb 2020
If you put this line after your line plotting, you'll see the basics of using the patch command:
patch([x1; x1(1)],[y1; y1(1)],'g')
The first two arguments are the (x,y) coordinates of the polygon that you want to fill. Notice how I "closed the loop" by appending the initial x1 and y1 points again, at the end of the vector. Here is the result:
I realize that that is not the exact area you want filled. But it gives you the idea.
To do what you really want, you'll need to similarly trace the outline of each of the polygons you want filled in, based on your input vectors. You'll need to combine some pieces of both x1 and x2 as input to patch, for some regions.

More Answers (1)

darova on 19 Feb 2020
x1 = linspace(0,1.5);
y1 = sin(x1);
x2 = linspace(0,2);
y2 = cos(x1);
[xc,yc] = polyxpoly(x1,y1,x2,y2); % find intersection point
ii1 = x1 > xc; % indices for the first curve
ii2 = x2 > xc; % indices for the second curve
patch([x1(ii1) flip(x2(ii2))], [y1(ii1) flip(y2(ii2))], 'r'); % fill right side
hold on
patch([x1(ii1) x2(~ii2)], [y1(ii1) y2(~ii2)], 'g'); % fill up/down
patch([x2(ii2) x1(~ii1)], [y2(ii2) y1(~ii1)], 'b'); % fill up/down
patch([x1(~ii1) flip(x2(~ii2))], [y1(~ii1) flip(y2(~ii2))], 'm'); % fill left side
hold off
The result
THe hole inside

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!