在Matlab中显示3-D绘图时出错

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

        =  0                  ,otherwise.

我在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

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

缺口

我认为您应该检查一下自己在做什么...逐行

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

但是,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)

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

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

figure(100);
surf(x, y, zz);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章