MATLAB: Error using ==> mesh at 80 Z must be a matrix, not a scalar or vector.

3d ploterror

Hi, I'm trying to plot this code, but I'm not sure what went wrong.
x=0:1:40;
y=0:1:40;
[X,Y]=meshgrid(x,y);
a=0.5;
b=0.5;
k=length(x);
gt=0.5;
o=20;
for v=1:1:k
if X(v)==0||Y(v)==0
Z(v)=(a.^2)*sqrt(exp(-o)*(o.^(X(v)+1))./factorial(X(v)+1))*sqrt(exp(-o)*(o.^(Y(v)+1))./factorial(Y(v)+1))*cos(gt*sqrt(X(v)+1))*cos(gt*sqrt(Y(v)+1))+(b.^2)*sqrt(exp(-o)*(o.^X(v))./factorial(X(v)))*sqrt(exp(-o)*(o.^Y(v))./factorial(Y(v)))*cos(gt*sqrt(X(v)))*cos(gt*sqrt(Y(v)));
else
Z(v)=2;
end
end
mesh(X,Y,Z)
xlabel('n');ylabel('m')
zlabel('P')

Best Answer

You are only iterating over the first column of X. You are using linear indexing into a 2D array, and you are only going as far as length(x) when the 2D array is length(x) by length(y).
I suggest that you do not loop at all. I suggest that you completely vectorize the construction of your Z in terms of X and Y, under the assumption that neither X nor Y is 0. And then use logical indexing to assign the 2 to the locations in Z corresponding to X or Y being 0.