필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
Martins Jancevskis
Martins Jancevskis 2019년 9월 1일
답변: Star Strider 2019년 9월 1일
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