Friday, October 22, 2010

Mesh plot in MATLAB


To create a mesh plot in MATLAB similar to this -

do the following.

  • Initialize vectors X and Y with the x- and y-coordinates.
  • For each pair of (x,y) values, compute the function value f(x,y), and store in matrix Z having the form -
Z(1,:) = [ f(y1,x1) f(y1,x2) ... f(y1,xn) ]
Z(2,:) = [ f(y2,x1) f(y2,x2) ... f(y2,xn) ]
and so on.
  • Run mesh(X,Y,Z) to the mesh plot.

E.g. Plot f(x,y) = 2x^2 + 12 xy + 7y^2 (shown in plot)
The code will look something like this -

%%%%%%%%%%%%%%%%%%%%
X = -1:.1:1;

Y=X;

% x's along columns
Xsq = X.*X;
for n=1:size(Y,2)
XsqM(n,:) = Xsq;
end
% y's along rows
Ysq = Y.*Y;
for n=1:size(X,2)
YsqM(:,n) = Ysq';
end

% x's change along a row (y fixed)
% y's change along a col (x fixed)
XY = Y'*X;

Z = 2.*XsqM + 12.*XY - 1.*YsqM;
mesh(X,Y,Z)
%%%%%%%%%%%%%%%%

No comments:

Post a Comment