How can I shade an interval in a calculus function with the area() function?
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Alfonso Rodriguez
am 9 Dez. 2024
Kommentiert: Star Strider
am 10 Dez. 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 Kommentare
Akzeptierte Antwort
Star Strider
am 9 Dez. 2024
Bearbeitet: Star Strider
am 9 Dez. 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 Kommentare
Star Strider
am 10 Dez. 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)
.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Creating, Deleting, and Querying Graphics Objects finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

