How do shade different area with specific y interval

1 view (last 30 days)
My codes are as follows:
clear
x = 0:0.01:9;
y = sqrt(x);
plot(x, y)
hold on;
x = 1:0.01:9;
[m n]=size(x)
y1=ones(1,n);
plot(x,y1,'r--')
hold on
x = 4:0.01:9;
[m n]=size(x)
y2=ones(1,n)*2;
plot(x,y2,'r--')
hold on
text(2.8, 2,'$y=\sqrt x$', 'interpreter','latex')
text(5.5, 0.2,'Shade this area by green')
text(5.5, 1.2,'Shade this area by red')
text(5.5, 2.2,'Shade this area by blue')

Accepted Answer

Wan Ji
Wan Ji on 25 Aug 2021
Hi, Wan-Yi Chiu
I add three more code lines after your code, then it works.
clear
x = 0:0.01:9;
y = sqrt(x);
y0 = y(end:-1:1);
x0 = x(end:-1:1);
plot(x, y)
hold on;
x = 1:0.01:9;
[m n]=size(x)
y1=ones(1,n);
plot(x,y1,'r--')
hold on
x = 4:0.01:9;
[m n]=size(x)
y2=ones(1,n)*2;
plot(x,y2,'r--')
hold on
text(2.8, 2,'$y=\sqrt x$', 'interpreter','latex')
text(5.5, 0.2,'Shade this area by green')
text(5.5, 1.2,'Shade this area by red')
text(5.5, 2.2,'Shade this area by blue')
fill([0,9,9,1,x0(x0<=1)],[0,0,1,1,y0(x0<=1)],'g')
fill([1,9,9,4,x0(x0>=1&x0<=4)],[1,1,2,2,y0(x0>=1&x0<=4)],'r')
fill([4,9,9,x0(x0>=4)],[2,2,3,y0(x0>=4)],'b')
The result figure

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!