Some examples of plotting 2d functions in Matlab.
How would you make a graph of on
in Matlab? You would
x
of gridpoints with linspace
x
plot(x,f)
to draw the graphFor example,
% Plot 1d graph of f(x) = (x-1)^2 on -3 < x < 3 x = linspace(-3, 3, 100); % create vector x of gridpoints f = (x-1).^2; % evaluate f(x) on gridpoints plot(x,f) % plot the graph xlabel('x') ylabel('f(x) = (x-1)^2')
Graphing a 2d function is very similar. For example, to make a graph of the function
on
x
and y
of gridpoints on linspace
X
and Y
of gridpoints on 2d mesh with meshgrid
X,Y
pcolor(x,y,f)
to draw the graph (or contour
, contourf
, surf
, surfc
)For example,
% Plot f(x,y) = 2*(x-1)^2 + (y-1)^2 on -4 < x < 4, -4 < y < 4 x = linspace(-4,4,30); % create 1d gridpoints on x and y axes y = linspace(-4,4,30); [X,Y] = meshgrid(x,y); % create 2d mesh of gridpoints over x,y F = 2*(X-1).^2 + (Y-1).^2; % evaluate the function f(x,y) over mesh pcolor(x,y,F); % or contour(X,Y,F), surf(x,y,F), etc. colorbar() % plot a colorbar xlabel('x'); ylabel('y'); title('f(x,y) = 2(x-1)^2 + (y-1)^2') shading interp % or faceted, flat
The function has gradient
Here's the Matlab code to make a contour plot of with its gradient superimposed as a quiver plot.
% Plot f(x,y) = x e^(-x^2 - y^2) with contours and its gradient as arrows. x = linspace(-2, 2, 30); y = linspace(-2, 2, 30); [X,Y] = meshgrid(x,y); F = X .* exp(-X.^2 - Y.^2); % evaluate f(x,y) on mesh contour(x,y,F); % draw contour plot of f % let dfdy = y component of grad F = df/dy dfdx = (1-2*X.^2) .* exp(-X.^2 - Y.^2); % evaluate dfdx on mesh dfdy = -2*X.*Y .* exp(-X.^2 - Y.^2); % evaluate dfdy on mesh hold on quiver(x,y,dfdx,dfdy); % draw quiver plot xlabel('x') ylabel('y') title('f(x,y) = x e^{-x^2 - y^2} with \nabla f arrow plot') colorbar()