How do I fill in the area between two lines and a curve that's not straight in MATLAB (the region is not a polygon)

StackOverflow https://stackoverflow.com/questions/12167974

Question

Using matlab's FILL function creates a filled region confined by a polygon with straight edges:

enter image description here

Unfortunately this leaves a small white region in the figure above, because the boundary of the region I want filled in is not a straight-edged polygon, but rather has a curved boundary on the left side. I have a curve (nearly parabolic but not exactly), and I want to fill in the region between two horizontal lines AND the curve itself. I also looked into the MATLAB function IMFILL, but with no luck.

Was it helpful?

Solution

What you need to do is make a polygon with more corners, so that it fits the curve more smoothly:

%# create a parabola and two straight lines
x = -3:0.1:3;
y = x.^2/4;
plot(x,y)
hold on, plot([-3 3],[1 1],'r',[-3 3],[2 2],'r')

%# create a polygon that hugs the parabola
%# note that we need to interpolate separately
%# for positive and negative x
x1 = interp1(y(x<0),x(x<0),1:0.1:2);
%# interpolate in reverse so that the corners are properly ordered
x2 = interp1(y(x>0),x(x>0),2:-0.1:1);

%# fill the area bounded by the three lines
fill([x1,x2],[1:0.1:2,2:-0.1:1],'g')

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top