Borrar filtros
Borrar filtros

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

12 visualizaciones (últimos 30 días)
friet
friet el 29 de Nov. de 2016
Comentada: Star Strider el 12 de Dic. de 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

Respuesta aceptada

Star Strider
Star Strider el 29 de Nov. de 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 comentarios
friet
friet el 12 de Dic. de 2016
Star Strider! You are the Best!!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Numerical Integration and Differentiation en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by