MATLAB: To 3Dplot a function that is inside a nested for loop

3dplotfunctionnested for loop

I am trying to plot a 3D figure out of 2D gaussian function 'z' . I need to plot the z values as a 3D plot
clear all;
clc;
XMin = -2.5;
XMax = 2.5;
YMin = XMin;
YMax = XMax;
increment = 0.01;
sigma = 1;
for x = XMin:increment:XMax
for y = YMin:increment:YMax
z = exp((-((x.^2)+(y.^2))./2)*(sigma.^2));
end
end
% Trying to plot a 3D figure

Best Answer

You are not saving the values of ā€˜zā€™ in your loop as a matrix.
However there is a more efficient way to do what you want, avoiding the (explicit) loops entirely:
XMin = -2.5;
XMax = 2.5;
YMin = XMin;
YMax = XMax;
increment = 0.01;
sigma = 1;
Xv = XMin:increment:XMax; % Assign Vector

Yv = YMin:increment:YMax; % Assign Vector
z = @(x,y) exp((-((x.^2)+(y.^2))./2)*(sigma.^2)); % Anonymous Function (For Ceonvenience)
[Xm,Ym] = ndgrid(Xv,Yv); % Generate Grid Matrices
figure
surf(Xv, Yv, z(Xm,Ym), 'EdgeColor','none') % Evaluate & Plot
grid on
Your grid is very dense, so setting the 'EdgeColor' to 'none' turns off the edges, allowing you to see the surface patches easily.