首页 > 解决方案 > 在MATLAB中填充两条直线曲线之间的区域

问题描述

我需要用“阴影灰色”颜色填充两条线的区域。我使用了以下代码:

M = [0.54, 0.7, 0.74, 0.78];
X1 = [0.007856, 0.008394, 0.008607, 0.012584];      %X1 values
X2 =  [0.007901, 0.008461, 0.008739, 0.011302];      %X2 values
xq = (0.54:0.000001:0.8);   %adding intervals to make line smoother
X3 = interpn(M,X1,xq,'pchip');  %other type: pchip, makima, spline etc.
X4 = interpn(M,X2,xq,'pchip');  %other type: pchip, makima, spline etc.
set(0,'defaulttextinterpreter','latex')

figure(1)
hold all; 
plot(xq, X3,'r-','LineWidth',1.5);
plot(xq, X4,'b--','LineWidth',1.5);

X=[xq,fliplr(xq)];           %create continuous x value array for plotting
Y=[X3,fliplr(X4)];           %create y values for out and then back

fill(X,Y,'g');    %plot filled area
xlabel('X','FontSize',12); % Label the x axis
ylabel('Y','FontSize',12); % Label the y axis
axis([0.5 0.8 0.007 0.013]);

然而,当我试图使线条更平滑时,填充命令并没有发生!我需要保持线条更平滑,同时用“阴影灰色”填充该区域。

任何帮助将不胜感激。

标签: matlabmatlab-figure

解决方案


您遇到的问题是它X3包含X4NaN 值。这发生在您尝试推断并在那里interpn添加 NaN 值的地方。

数组xq以 0.8 结束,而输入数据M以 0.78 结束。你也应该xq在 0.78 结束。最好的方法如下:

xq = M(1):0.000001:M(end);

虽然请注意间隔非常小,这会导致要绘制的数据点太多,但没有必要拥有这么多点来绘制平滑图。我建议你linspace改用:

xq = linspace(M(1), M(end), 1000);

这里,1000是点数。


推荐阅读