Im trying to find the area of the shaded parts of the curve. Blue for above the threshold and grey for below it. In the script you can change the ratio of blue to grey by adjusting the level value. When level is set to 2 (pic 1) the areas should be equal. When level is set to 1.6 (pic 2) the blue should have greater area than the grey, etc... Any thoughts on how to find the areas under the curve below and above the threshold?
pic 1:
pic 2:
My code:
%% Example
x = 0:.01:4*pi;% x data
y = sin(x)+2;% y data
level = 2;% level
plot(x, y)
hold on
x_interest = 0:.01:x(length(y));
y_interest = sin(x_interest)+2;
xlim ([0 x(length(y))])
% Shaded area above level
area(x_interest, max(y_interest, level), level, ...
'EdgeColor', 'none', 'FaceColor', [.6 .7 .8], ...
'ShowBaseLine', 'off');
% Shaded area below level
area(x_interest, min(y_interest, level), level, ...
'EdgeColor', 'none', 'FaceColor', [.5 .5 .5], ...
'ShowBaseLine', 'off');
%%== This did not work ==%%
above = find(y_interest >= level);
below = find(y_interest <= level);
A_above = trapz(above)
A_below = trapz(below)
%% Integrate
plot(x, sin(x)+2)
fun = @(x) sin(x)+2;
integral(fun, 0, x(length(y)))
A = trapz(x,y)
In the general sense, the function trapz(x,y)
(where x
and y
are vectors of same length) estimates the area under the curve f(x) = y
. This area is sandwiched by the function f(x)
and the x-axis.
For A_above
, you want to estimate the area between curves f1(x_interest) = max(y_interest, level)
and f2(x_interest) = level
. That is same as the area under curve f1(x_interest)
shifted down by level
. So this can be evaluated by:
A_above = trapz(x_interest, max(y_interest, level)-level)
Similarly, for A_below
:
A_below = -trapz(x_interest, min(y_interest, level)-level)