在matlab中显示3-D Plot时出错

coo*_*ool 2 matlab

我想在matlab中绘制以下函数:
f(x,y) = sqrt(1-x^2-4y^2) ,(if (x^2+4*y^2) <=1 )

        =  0                  ,otherwise.
Run Code Online (Sandbox Code Playgroud)

我在matlab中编写了以下代码:

  x=0:0.1:10;  
  y=0:0.1:10;
  z=x.^2+4*y.^2;
  if (z <=1)
   surf(x,y,z);

  else
   surf(x,y,0);
  end
Run Code Online (Sandbox Code Playgroud)

但会显示以下错误:
surface: rows (Z) must be the same as length (Y) and columns (Z) must be the same as length (X)
如何避免此错误...

Nic*_*ick 5

我想你应该真正检查你在做什么......一行一行

x = 0:0.1:10; % define x-array 1x101
y = 0:0.1:10; % define y-array 1x101
z = x.^2+4*y.^2; % define z-array 1x101
Run Code Online (Sandbox Code Playgroud)

但是,surf需要一个矩阵作为输入,z因此这里使用的语法不正确.

相反,创建一个x网格和y网格:

[xx, yy] = meshgrid(x, y); % both being 101x101 matrices

zCheck = xx.^2+4*yy.^2; % 101x101
zz     = sqrt(1-xx.^2-4*y.^2)
Run Code Online (Sandbox Code Playgroud)

关于if语句,您最好在绘制之前更改值:

zz(zCheck > 1) = 0; % replace the values larger than 1 by zero (use logical indexing)

figure(100);
surf(x, y, zz);
Run Code Online (Sandbox Code Playgroud)