Search code examples
matlabsurf

Creating a surface correctly


I want to create and show the surface z=x*exp(-x^2-y^2) in the section x,y~[-10;10]. I am trying to use:

x=-10:10;
y=-10:10;
z=x*exp(-x^2-y^2);
[X,Y,Z]=meshgrid(x,y,z);
surf(X,Y,Z);

and getting:

"Error using ^ Inputs must be a scalar and a square matrix. To compute elementwise POWER, use POWER (.^) instead."

I understand that x is a vector and so this is not a logical statement. Never the less, I do not have an Idea as to how to create this surface?


Solution

  • You'll want to use meshgrid before computing z so that you compute a value for z for each combination of x and y. Also you'll want to use element-wise operators (.^ and .*) to create z

    % Create all permutations of x and y
    [x, y] = meshgrid(-10:10,-10:10);
    
    % Compute z for each permutation
    z = x .* exp(-x.^2 - y.^2);
    
    % Plot as a surface
    surf(x, y, z)