MATLAB: Plot multivariable function, find critical points

MATLAB

i need to plot a multivariable (x1,x2) function f_a in matlab, and find its critical points. I plotted it, but in order to find the critical points, i need to set the partial derivatives to zero then solve. when i try setting the partial derivatives to zero using diff(f_a,x1),it gives me an error.
[x1,x2] = meshgrid(-5:.2:5);
f_a = x1.^2 + x2.^2 +2.*x1.*x2;
figure(1)
surf(x1,x2,f_a)
fa1=diff(f_a,x1)

Best Answer

Use the gradient function to calculate the derivative.
Try this:
[x1,x2] = meshgrid(-5:.2:5);
f_a = x1.^2 + x2.^2 +2.*x1.*x2;
fa1 = gradient(f_a, 0.2, 0.2); % Derivative
zv = contour(x1,x2,fa1, [0; 0]); % Critical Points
figure(1)
surf(x1,x2,f_a)
hold on
plot3(zv(1,2:end), zv(2,2:end), zeros(1,size(zv,2)-1), 'r', 'LineWidth',2)
hold off
Related Question