How can I shade an interval in a calculus function with the area() function?

27 次查看(过去 30 天)
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.

采纳的回答

Star Strider
Star Strider 2024-12-9,22:10
编辑:Star Strider 2024-12-9,22:15
I prefer the patch function, simply because I have more experience with it.
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 个评论
Star Strider
Star Strider 2024-12-10,19:31
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)
.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by