Clear Filters
Clear Filters

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

3 views (last 30 days)
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

Accepted Answer

Star Strider
Star Strider on 1 Sep 2019
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.

More Answers (0)

Categories

Find more on Data Exploration in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!