How can I shade an interval in a calculus function with the area() function?
7 views (last 30 days)
Show older comments
Alfonso Rodriguez
on 9 Dec 2024
Commented: Star Strider
on 10 Dec 2024
I want to shade the area between an interval in a math function like the example below. This is for a calculus class. I was thinking on using the area() function. Thanks.

0 Comments
Accepted Answer
Star Strider
on 9 Dec 2024
Edited: Star Strider
on 9 Dec 2024
Try this —
x = linspace(0, 1);
y = 1 + 0.5*sin(2*pi*x);
figure
plot(x, y)
xlim([0 1.25])
ylim([0 2])
Lv = x >= 0.2 & x <= 0.6;
A = trapz(x(Lv), y(Lv));
hold on
patch([x(Lv) flip(x(Lv))], [zeros(size(y(Lv))) flip(y(Lv))], [1 1 1]*0.75)
hold off
text(0.2, -0.15, 'x = a')
text(0.6, -0.15, 'x = b')
xapf = @(x,pos,xl) pos(3)*(x-min(xl))/diff(xl)+pos(1); % 'x' Annotation Position Function
yapf = @(y,pos,yl) pos(4)*(y-min(yl))/diff(yl)+pos(2); % 'y' Annotation Position Function
xl = xlim;
yl = ylim;
pos = gca().Position;
annotation('arrow', xapf([0.4 0.5],pos, xl), yapf([0.8 1.4],pos, yl))
text(0.5, 1.4, sprintf('A = %.2f', A), 'Vert','bottom')
text(x(end), y(end), 'y = f(x)', 'Horiz','left')
EDIT —
Forgot the ‘y = f(x)’ text object. Now added.
.
2 Comments
Star Strider
on 10 Dec 2024
As always, my pleasure!
A slightly more informative version —
x = linspace(0, 1);
y = 1 + 0.5*sin(2*pi*x);
figure
plot(x, y, LineWidth=2)
xlabel('$x$', Interpreter='LaTeX', FontSize=20, FontWeight='bold')
ylabel('$y$', Interpreter='LaTeX', FontSize=20, FontWeight='bold')
xlim([0 1.25])
ylim([0 2])
Lv = x >= 0.2 & x <= 0.6;
A = trapz(x(Lv), y(Lv));
hold on
patch([x(Lv) flip(x(Lv))], [zeros(size(y(Lv))) flip(y(Lv))], [1 1 1]*0.5, EdgeColor='none', FaceAlpha=0.5)
hold off
text(0.2, -0.15, '$x = a$', Interpreter='LaTeX', FontSize=12)
text(0.6, -0.15, '$x = b$', Interpreter='LaTeX', FontSize=12)
xapf = @(x,pos,xl) pos(3)*(x-min(xl))/diff(xl)+pos(1); % 'x' Annotation Position Function
yapf = @(y,pos,yl) pos(4)*(y-min(yl))/diff(yl)+pos(2); % 'y' Annotation Position Function
xl = xlim;
yl = ylim;
pos = gca().Position;
annotation('arrow', xapf([0.4 0.6],pos, xl), yapf([0.8 1.1],pos, yl))
text(0.6, 1.1, sprintf('$A = %.2f$', A), 'Vert','bottom', Interpreter='LaTeX', FontSize=14)
text(x(end)+0.05, y(end), '$y = f(x)$', 'Horiz','left', 'Vert','middle', Interpreter='LaTeX', FontSize=12)
text(0.5,1.6, '$$\int_a^bf(x)\ dx$$', Interpreter='LaTeX', FontSize=20)
.
More Answers (0)
See Also
Categories
Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
