Shade the region between the lines and xy axis
17 views (last 30 days)
Show older comments
Tahlea Perry
on 22 Feb 2021
Commented: Star Strider
on 22 Feb 2021
Hi! I am trying to shade the region I coloured in, but I can't figure it out! help!
My code for the graph:
clear all
x=linspace(-2,8);
y1=(8-2*x);
plot(x,y1)
hold on
y3= (5+2.5*x);
plot(x,y3)
y4=(0*x);
plot(x,y4)
y5=xline(0)
grid on
box on
hold off
0 Comments
Accepted Answer
Star Strider
on 22 Feb 2021
Edited: Star Strider
on 22 Feb 2021
Try this:
x=linspace(-2,8);
y1=@(x)(8-2*x);
y3= @(x)(5+2.5*x);
y4=@(x)(0*x);
y5=xline(0);
y1_xint = fzero(@(x) y1(x), 1);
y1y3_int = fzero(@(x) y1(x) - y3(x), 1);
figure
plot(x,y1(x))
hold on
plot(x,y3(x))
plot(x,y4(x))
patch([0 y1y3_int y1y3_int 0], [0 0 y3(y1y3_int) y3(0)],'g', 'EdgeColor','g')
patch([y1y3_int y1_xint [0 0]+y1y3_int], [0 0 y3(y1y3_int) y3(0)],'g', 'EdgeColor','g')
grid on
box on
hold off
producing:
I created anonymous functions from the line expressions, since that makes the calculations easier. The fzero calls calculate the line intercepts and the ‘y1’ intercept with the x-axis. The area is filled using two patch calls, one for each segment of the area. You can see the segments by removing the 'EdgeColor' arguments and their paired values.
EDIT — (22 Feb 2021 at 20:42)
Another approach using logical vectors and comparisons —
figure
plot(x,y1(x))
hold on
plot(x,y3(x))
plot(x,y4(x))
Lv = x>=0 & x<=y1_xint;
fill([x(Lv) fliplr(x(Lv))], [min(y1(x(Lv)),y3(x(Lv))) zeros(size(x(Lv)))], 'g')
grid on
box on
hold off
and producing essentially the same figure.
.
2 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!