Shade the region between the lines and xy axis

19 visualizaciones (últimos 30 días)
Tahlea Perry
Tahlea Perry el 22 de Feb. de 2021
Comentada: Star Strider el 22 de Feb. de 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

Respuesta aceptada

Star Strider
Star Strider el 22 de Feb. de 2021
Editada: Star Strider el 22 de Feb. de 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 comentarios
Tahlea Perry
Tahlea Perry el 22 de Feb. de 2021
Thank you so much! You are the best
Star Strider
Star Strider el 22 de Feb. de 2021
As always, my pleasure!
I very much appreciate your compliment!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Just for fun en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by