# Fill the region between two lines

627 views (last 30 days)

Show older comments

Hello all,

I plot two functions and then I want to fill the region between them in red (for example).

Could you please suggest me the function to do this?

Thanks

x=0:0.1:10;

y1=exp(-x/2);

y2=exp(-x/3);

figure

hold on

plot(x,y1)

plot(x,y2)

##### 0 Comments

### Accepted Answer

Star Strider
on 5 Feb 2019

x=0:0.1:10;

y1=exp(-x/2);

y2=exp(-x/3);

figure

hold all

plot(x,y1)

plot(x,y2)

patch([x fliplr(x)], [y1 fliplr(y2)], 'g')

hold off

To use it, create a closed area (the reason for the fliplr calls, since they create the closed area), and choose the color.

##### 0 Comments

### More Answers (1)

YT
on 5 Feb 2019

##### 3 Comments

TwoPhotons
on 12 Jul 2023

Walter Roberson
on 12 Jul 2023

I recently posted related code that only depends on the x and y being vectors, rather than being row vectors; see https://www.mathworks.com/matlabcentral/answers/1993578-shading-area-between-two-functions#answer_1269778

When you use [a b] where a and b are row vectors, then you end up with a row vector that is the contents of a followed by the contents of b, and in this case the two do not need to be the same size. If one of the two of a or b is a row vector and the other is a column vector (with more than one row) then [a b] would give an error. If both a and b are column vectors, then if they are not the same size you would get an error; if a and b are both column vectors the same size then [a b] would result in a 2d matrix with two columns, the first being copied from a and the second being copied from b.

To use patch() to fill a single area, then it needs to be passed vectors of values. patch() does not care whether it is passed row vectors or column vectors, as long as they are vectors.

But as I explored above if you have [a b] and they are both column vectors then [a b] would not be a vector, it would be a 2D array -- which is not going to do what you want for patch()

If you knew ahead of time that a and b are both column vectors then you could use [a; b] to generate a single column vector that is the contents of a followed by the contents of b. But if all you know ahead of time is that a and b are vectors, then you need to be careful about whether you use [a b] or [a; b]

Also, code that uses fliplr() or flipud() to compute the path "back around" is making assumptions about whether its inputs are row or columns.

It is not difficult to work around these uncertainties; see the above link for the way I coded it there.

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!