views:

26

answers:

1

I am trying to graph the following Gaussian function in MATLAB (should graph in 3 dimensions) but I am making some mistakes somewhere. What is wrong?

sigma = 1
for i = 1:20
    for j = 1:20
        z(i,j) = (1/(2*pi*sigma^2))*exp(-(i^2+j^2)/(2*sigma^2));
    end
end
surf(z)
+1  A: 

The problem you are likely having is that you are evaluating the Gaussian over the range of 1 to 20 for both i and j. Since sigma is 1, you are only going to see a segment of one side of the Gaussian (not including the center at [i,j] = [0,0]), and the values of z from 3 to 20 in each direction are very close to 0.

Instead of using for loops, you can do things "the MATLAB way" by creating matrices of x and y values using the function MESHGRID and performing element-wise operations on them to compute and plot z:

[x,y] = meshgrid(-4:0.1:4);  %# Use values from -4 to 4 in x and y directions
z = (1/(2*pi*sigma^2)).*exp(-(x.^2+y.^2)./(2*sigma^2));  %# Compute z
surf(x,y,z);  %# Plot z
gnovice