在MATLAB中的特定点之间填充两条曲线之间的区域

时间:2016-02-06 23:32:47

标签: matlab

我有一个PSD图,我正在尝试计算和填充MATLAB中两条曲线之间的区域,分别为两个不同的频率范围(8-30 Hz和70-100 Hz)。

这是我用于生成绘图的代码,其中f =频率和ZmZ代表两个条件的Z分数:

plot(f,Zm,f,Z,'LineWidth',2)
xlim([0 100]);
xlabel('Frequency (Hz)');
ylabel('Normalized Power');

我相信我需要使用trapz函数来计算填充空间的区域和填充函数,但我不确定如何使用这些函数在特定频率之间执行计算。

为了使事情进一步复杂化,我想只遮蔽Zm 0的频率。 Z表示频率为70-100Hz。

这是有问题的情节:

plot

2 个答案:

答案 0 :(得分:0)

为了计算面积,这样的事情可能会起作用:

r1=(f>=8).*(f<=30);
r2=(f>=70).*(f<=100);
area=trapz(f(r1),Zm(r1)-Z(r1))+trapz(f(r2),Zm(r2)-Z(r2));

要填写第一个区域,您可以尝试:

f1=f(r1);
Zm1=Zm(r1);
Z1=Z(r1);
for i=1:length(f1)-1
    fill([f1(i) f1(i+1) f1(i+1) f1(i)],[Z1(i) Z1(i+1) Zm1(i+1) Zm1(i)],'blue');
end

第二个类似的东西。

如果只想填充Zm小于Z的区域,可以使用相同的代码,但在for循环中添加if。类似的东西:

for i=1:length(f1)-1
    if Zm1(i)<Z1(i) && Zm1(i+1)<Z1(i+1)
        fill([f1(i) f1(i+1) f1(i+1) f1(i)],[Z1(i) Z1(i+1) Zm1(i+1) Zm1(i)],'blue');
    end
end

答案 1 :(得分:0)

这是我最终使用的代码(这些建议的组合):

%// Fill in area between low frequency bands
f1=f(r1)'; %'// <-- this prevents string markdown
Zm1=Zm(r1);
Z1=Z(r1);

mask = Zm1 <= Z1;
fx = [f1(mask), fliplr(f1(mask))];
fy = [Zm1(mask),fliplr(Z1(mask))];
hold on
fill_color = [.040 .040 1];
fh = fill(fx,fy,fill_color);
hold off
%fh.EdgeColor = 'none';

delete(fh)

hold on
output = [];
%// Calculate t in range [0 1]
calct = @(n) (n(3,1)-n(2,1))/(n(3,1)-n(2,1)-n(3,2)+n(2,2));
%// Generate interpolated X and Y values
interp = @(t,n) n(:,1) + t*(n(:,2) - n(:,1));

for i=1:length(f1)
%// If y2 is below y1, then we don't need to add this point.
if Z1(i) <= Zm1(i)
    %// But first, if that wasn't true for the previous point, then add the
    %// crossing.
    if i>1 && Z1(i-1) > Zm1(i-1)
        neighborhood = [f1(i-1), f1(i); Zm1(i-1), Zm1(i); Z1(i-1), Z1(i)];
        t = calct(neighborhood);
        output(:,end+1) = interp(t,neighborhood);
    end
else
%// Otherwise y2 is above y1, and we do need to add this point. But first
%// ...
    %// ... if that wasn't true for the previous point, then add the
    %// crossing.
    if i>1 && Z1(i-1) <= Zm1(i-1)
        neighborhood = [f1(i-1), f1(i); Zm1(i-1), Zm1(i); Z1(i-1), Z1(i)];
        t = calct(neighborhood);
        output(:,end+1) = interp(t,neighborhood);
    end

    %// add this point.
    output(:,end+1) = [f1(i); Z1(i); Zm1(i)];
end
end

xout = output(1,:);
topout = output(2,:);
botout = output(3,:);
fh = fill([xout fliplr(xout)],[botout fliplr(topout)],fill_color);
fh.EdgeColor = 'none';
uistack(fh,'bottom')
hold off

我重复了这个频率。

结果图:enter image description here