Fill the region between two lines
484 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Star Strider
2019-2-5
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 个评论
更多回答(1 个)
YT
2019-2-5
3 个评论
TwoPhotons
2023-7-12
Thank you for this comment. I spent a while looking for the error in my code. All threads related to this point to the OG thread listed here by YT, but there is no mention of this stipulation there that I could find, and it isn't really clear why it is needed.
Walter Roberson
2023-7-12
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!