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

3 次查看(过去 30 天)
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

采纳的回答

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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Exploration 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by