I wanted to draw the following function in matlab:
f(x,y) = sqrt(1-x^2-4y^2) ,(if (x^2+4*y^2) <=1 )
= 0 ,otherwise.
I wrote the following code in 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
but the following error is displayed:
surface: rows (Z) must be the same as length (Y) and columns (Z) must be the same as length (X)
How shall I avoid this error...
I think you should really check what you are doing... line by line
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
However, surf
needs a matrix as input for z
therefore the syntax as you use it here is incorrect.
Instead, create a x-grid and y-grid:
[xx, yy] = meshgrid(x, y); % both being 101x101 matrices
zCheck = xx.^2+4*yy.^2; % 101x101
zz = sqrt(1-xx.^2-4*y.^2)
Concerning the if statement, you better change the values before plotting:
zz(zCheck > 1) = 0; % replace the values larger than 1 by zero (use logical indexing)
figure(100);
surf(x, y, zz);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.