MATLAB: Calculate area between unknown curve and straight line

integrationnumerical integration

How can I calculate areas between these unknown curve and line, see image. The line is not zero.
How can I use trapz in this case? it would calculate the area under the curve from zero line
Areas under the line should be negative
theta=0:10:710;
T=[0 15 813 964 1016 936 775 642 695 850 1032 1029 904 712 608 592 545 344 0 -346 -540 -578 -569 -636 -784 -877 -815 -570 -325 -191 -203 -237 -165 5 149 146 0 -143 -149 -7 164 236 201 191 324 570 815 879 786 640 569 574 538 344 0 -343 -541 -578 -574 -645 -792 -893 -836 -606 -380 -264 -298 -369 -332 -197 -56 2];
W=trapz(theta,T);
T_avg=W/710;
plot(theta,T)
hold on
plot(theta,T_avg*ones(size(theta)))

Best Answer

The areas below the line are negative:
AboveLine = T>=T_avg; % Logical Vector
AreaAboveLine = trapz(theta(AboveLine), T(AboveLine))
AreaBelowLine = trapz(theta(~AboveLine), T(~AboveLine))
AreaTotal = AreaAboveLine + AreaBelowLine
producing:
AreaAboveLine =
235685
AreaBelowLine =
-147420
AreaTotal =
88265
EDIT —
Try this:
theta=0:10:710;
T=[0 15 813 964 1016 936 775 642 695 850 1032 1029 904 712 608 592 545 344 0 -346 -540 -578 -569 -636 -784 -877 -815 -570 -325 -191 -203 -237 -165 5 149 146 0 -143 -149 -7 164 236 201 191 324 570 815 879 786 640 569 574 538 344 0 -343 -541 -578 -574 -645 -792 -893 -836 -606 -380 -264 -298 -369 -332 -197 -56 2];
W=trapz(theta,T);
T_avg=W/710;
plot(theta,T)
hold on
plot(theta,T_avg*ones(size(theta)))
hold off
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0); % Returns Approximate Zero-Crossing Indices Of Argument Vector
Tzx = zci(T - T_avg); % Zero-Crossing Indices
Tidx = [1; Tzx; numel(T)]; % All Relevant Indices
for k = 1:numel(Tidx)-1
idxrng = Tidx(k):Tidx(k+1);
Areas(k) = trapz(theta(idxrng), T(idxrng)-T_avg);
ctrs(k,:) = [mean(theta(idxrng)) mean(T(idxrng))];
end
for k = 1:size(ctrs,1)
text(ctrs(k,1),ctrs(k,2), sprintf('%.0f', Areas(k)), 'HorizontalAlignment','left', 'VerticalAlignment','middle'
end
Calculate area between unknown curve and straight line - 2019 06 30.png
Make appropriate changes to get the result you want.