%% Find the Derivatives of a Surface Using the differentiate Function
% You can use the differentiate method to compute the gradients of a fit and then use the quiver function to plot these gradients as arrows. This example plots the gradients over the top of a contour plot.
% Create the derivation points and fit the data.

x = [0.64;0.95;0.21;0.71;0.24;0.12;0.61;0.45;0.46;...
0.66;0.77;0.35;0.66];
y = [0.42;0.84;0.83;0.26;0.61;0.58;0.54;0.87;0.26;...
0.32;0.12;0.94;0.65];
z = [0.49;0.051;0.27;0.59;0.35;0.41;0.3;0.084;0.6;...
0.58;0.37;0.19;0.19];
fo = fit( [x, y], z, 'poly32', 'normalize', 'on' );
[xx, yy] = meshgrid( 0:0.04:1, 0:0.05:1 );

% Compute the gradients of the fit using the differentiate function.

[fx, fy] = differentiate( fo, xx, yy );

% Use the quiver function to plot the gradients.

plot( fo, 'Style', 'Contour' );
hold on
h = quiver( xx, yy, fx, fy, 'r', 'LineWidth', 2 );
hold off
colormap( copper )

%
% If you want to use derivatives in an optimization, you can, for example, implement an objective function for fmincon as follows.
% function [z, g, H] = objectiveWithHessian( xy )
%         % The input xy represents a single evaluation point
%         z = f( xy );
%         if nargout > 1
%             [fx, fy, fxx, fxy, fyy] = differentiate( f, xy );
%             g = [fx, fy];
%             H = [fxx, fxy; fxy, fyy];
%         end
%     end
% Copyright 2020 The MathWorks, Inc.