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

조회 수: 34 (최근 30일)
friet
friet 2016년 11월 29일
댓글: Star Strider 2016년 12월 12일
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

채택된 답변

Star Strider
Star Strider 2016년 11월 29일
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
friet
friet 2016년 12월 12일
Star Strider! You are the Best!!
Star Strider
Star Strider 2016년 12월 12일
Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by