使用 trapz 和 MATLAB 计算阈值上方和下方曲线下的阴影区域
Calculate the shaded area under the curve above and below a threshold using trapz and MATLAB
我正在尝试计算曲线阴影部分的面积。蓝色表示高于阈值,灰色表示低于阈值。在脚本中,您可以通过调整级别值来更改蓝色与灰色的比例。当级别设置为 2(图 1)时,区域应该相等。当级别设置为 1.6(图 2)时,蓝色的面积应该大于灰色,等等......关于如何找到曲线下低于和高于阈值的区域有什么想法吗?
图1:
图2:
我的代码:
%% 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)
在一般意义上,函数trapz(x,y)
(其中x
和y
是相同长度的向量)估计曲线下的面积f(x) = y
。该区域被函数 f(x)
和 x-axis.
夹在中间
对于 A_above
,您想要估计曲线 f1(x_interest) = max(y_interest, level)
和 f2(x_interest) = level
之间的面积。这与曲线 f1(x_interest)
下移 level
的面积相同。所以这可以通过以下方式评估:
A_above = trapz(x_interest, max(y_interest, level)-level)
同样,对于A_below
:
A_below = -trapz(x_interest, min(y_interest, level)-level)
图1:
图2:
我的代码:
%% 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)
在一般意义上,函数trapz(x,y)
(其中x
和y
是相同长度的向量)估计曲线下的面积f(x) = y
。该区域被函数 f(x)
和 x-axis.
对于 A_above
,您想要估计曲线 f1(x_interest) = max(y_interest, level)
和 f2(x_interest) = level
之间的面积。这与曲线 f1(x_interest)
下移 level
的面积相同。所以这可以通过以下方式评估:
A_above = trapz(x_interest, max(y_interest, level)-level)
同样,对于A_below
:
A_below = -trapz(x_interest, min(y_interest, level)-level)