简体   繁体   English

获取 matlab `surf` 到 plot 一个 function 在该地区的任何地方都不存在

[英]Get matlab `surf` to plot a function that doesn't exist everywhere in the region

I'm trying to use matlab to create a surface plot of a function that has a limited domain [it's a square root, and the argument goes negative].我正在尝试使用 matlab 创建具有有限域的 function 的表面 plot [它是平方根,并且参数变为负数]。

x = [-2:0.02:4]
y = [-6:0.1:6]
[X,Y] = meshgrid(x,y)

If I do如果我做

surf(X,Y,sqrt(9-(X-1).*(X-1)-Y.*Y/4))

I get an error message because the function is imaginary outside of an ellipse.我收到一条错误消息,因为 function 在椭圆之外是虚构的。 So I could do所以我可以做

surf(X,Y,real(sqrt(9-(X-1).*(X-1)-Y.*Y/4)))

But then it's 0 outside of the domain.但是在域外它是 0。 Really I'd like it to just not plot anything at all.真的,我希望它根本没有 plot 任何东西。

The only idea I have is to modify Y so that for each X , it's limited to the values where the function is defined.我唯一的想法是修改Y ,以便对于每个X ,它仅限于定义 function 的值。 But I'd really like a way to say 'just don't plot those parts' so that I don't have to calculate the domain each time.但我真的很想用一种方式说“不要 plot 那些部分”,这样我就不必每次都计算域。

Exploiting the fact that NaNs are usually ignored by graphical routines, you could use:利用图形例程通常忽略 NaN 的事实,您可以使用:

x = [-2:0.02:4];
y = [-6:0.1:6];
[X,Y] = meshgrid(x,y);
clear x y;

W=sqrt(9-(X-1).*(X-1)-Y.*Y/4);
Z=nan(size(W));
W_isreal=abs(imag(W))<=eps();
Z(W_isreal)=real(W(W_isreal));
clear W W_isreal;

surf(X,Y,Z);

Notice that this approach introduces unsightly artifacts near z=0:请注意,这种方法在 z=0 附近引入了难看的伪影:

结果

A more elegant approach that avoids such gaps near z=0 could be:避免 z=0 附近出现此类间隙的更优雅的方法可能是:

[X,Y,Z]=ellipsoid(1,0,0,3,6,3);
surf(X,Y,Z);
zlim([0 Inf]);

% Verify computations
W=9-(X-1).*(X-1)-Y.*Y/4;
W_istruenegative=(W<=-1e-6);
if any(W_istruenegative(:))
  error('Our ellipsoid looks invalid.');
end
if any( abs(sqrt(abs(W(:))) - abs(Z(:))) > 1e-6 ) %verify ellipsoid
  error('Our ellipsoid looks invalid.');
end
clear W W_istruenegative;

改进的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM