Effacer les filtres
Effacer les filtres

How can I calculate the area under a graph (Shaded area)?

12 vues (au cours des 30 derniers jours)
friet
friet le 29 Nov 2016
Commenté : Star Strider le 12 Déc 2016
Hello,
I am trying to calculate the area of the shaded area shown in the graph. This is my Matlab code. When I use trapz keyword it gives me the whole area. Is there any way to calculate the shaded area 1 and area 2 which are separated by the dotted lines.
clear all
clc
close all
x=0:0.1:3.14;
y=sin(4*x).*sec(3*x);
yy = zeros(1,length(x));
yy(:) = 0;
y1=-20:0.1:20;
x1 = ones(1,length(y1));
x1(:) = 0.5;
plot(x,y,x,yy,'--',x1,y1,'--')
trapx(x,y)
Is there also any way to select area 1 and paint it with different colors using matlab code.
Thanks

Réponse acceptée

Star Strider
Star Strider le 29 Nov 2016
Try this:
x=0:0.1:3.14;
y=sin(4*x).*sec(3*x);
yy = zeros(1,length(x));
yy(:) = 0;
y1=-20:0.1:20;
x1 = ones(1,length(y1));
x1(:) = 0.5;
area_1 = trapz(x(x<=0.5), y(x<=0.5)); % Calculate ‘Area #1’
xc = find((y .* circshift(y, [0 1])) < 0); % Define ‘y’ Zero-Crossings
idx_rng = xc(1)-1:xc(1); % Index Range Including Zero-Crossing
x0 = interp1(y(xc(1)-1:xc(1)), x(xc(1)-1:xc(1)), 0); % Find ‘x’ At Zero Crossing
area_2 = trapz([0.5 x0], [y(x == 0.5) 0]); % Calculate ‘Area #2’
plot(x,y,x,yy,'--',x1,y1,'--')
hold on
ha1 = area(x(x<=0.5), y(x<=0.5), 'FaceColor','g');
ha2 = area([0.5 x0], [y(x == 0.5) 0], 'FaceColor','r');
hold off
A1str = sprintf('Area 1 = %6.3f', area_1);
A2str = sprintf('Area 2 = %6.3f', area_2);
legend([ha1 ha2], A1str, A2str)
I colored ‘area2’ for clarity, and to show the value in the legend. Make whatever changes you need to. Note that this code is specific to your Question as you posted it, and while the ideas will generalise to similar applications, the code itself will not.
  14 commentaires
friet
friet le 12 Déc 2016
Star Strider! You are the Best!!
Star Strider
Star Strider le 12 Déc 2016
Thank you!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Numerical Integration and Differentiation dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by