使用trapz和MATLAB计算曲线下方和下方曲线下的阴影区域

时间:2017-01-12 20:17:50

标签: matlab matlab-figure area curve

enter image description here我试图找到曲线阴影部分的区域。蓝色高于阈值,灰色低于它。在脚本中,您可以通过调整级别值来更改蓝色与灰色的比率。当level设置为2(pic 1)时,区域应该相等。当水平设置为1.6(图2)时,蓝色应该具有比灰色等更大的面积...有关如何找到曲线下方和高于阈值的区域的任何想法?

图1: pic 1

图2: pic 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)

1 个答案:

答案 0 :(得分:1)

在一般意义上,函数trapz(x,y)(其中xy是相同长度的向量)估计曲线下的区域f(x) = y。该区域由函数f(x)和x轴夹在中间。

对于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)