In: Mechanical Engineering
Plot the contour plot and the gradient (shown by arrows) for the function
f(x, y) = -x2 + 2xy + 3y2
Consider the function f(x, y) = -x2 + 2xy + 3y2
The objective is to draw the contour plot.
Firstly, generate a set of data for x and y range a using ‘meshgrid’ command.
Then based on these, calculate the data function and obtain differential x and y.
Using these differential values and ‘gradient’ command first order derivatives can be found.
The contour is plotted using ‘contour’ command for x, y and function values. Then for the contour and gradient, arrows are shown using ‘quiver’ command.
Mat-lab code for above problem is provided below.
Save this program as ‘Required problem’.
% Plot the contour plot and gradient (shown by arrows) for the function
clc; clear;
[x,y] = meshgrid(-2:0.25:2);
f=-x.^2+2*x.*y+3*y.^2;
dx = x(1,2) - x(1,1);
dy = y(2,1) - y(1,1);
[df_dx,df_dy] = gradient(f, dx, dy);
contour(x,y,f);
xlabel(\'x\');
ylabel(\'y\');
hold on;
quiver(x,y,df_dx,df_dy);
hold off;