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

조회 수: 7 (최근 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일
편집: Star Strider 2024년 12월 9일
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
Alfonso Rodriguez
Alfonso Rodriguez 2024년 12월 10일
Thank you Star Strider. This will be wonderful for my students.
Star Strider
Star Strider 2024년 12월 10일
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에서 Creating, Deleting, and Querying Graphics Objects에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by