%% Compute Common Objective and Constraint Efficiently
% If your problem involves a common, time-consuming function to compute the objective and nonlinear constraint, you can save time by using the 'ReuseEvaluation' name-value pair argument. The rosenbrocknorm function computes both the Rosenbrock objective function and the norm of the argument for use in the constraint \|x\|^2 \le 4.

type rosenbrocknorm

% Create a 2-D optimization variable x. Then convert rosenbrocknorm to an optimization expression by using fcn2optimexpr and specifying 'ReuseEvaluation'.

x = optimvar('x',2);
[f,c] = fcn2optimexpr(@rosenbrocknorm,x,'ReuseEvaluation',true);

% Create objective and constraint expressions from the returned expressions. Include the objective and constraint expressions in an optimization problem. Review the problem using show.

prob = optimproblem('Objective',f);
prob.Constraints.cineq = c <= 4;
show(prob)

% Solve the problem starting from the initial point x0.x = [-1;1], timing the result.

x0.x = [-1;1];
tic
[sol,fval,exitflag,output] = solve(prob,x0)
toc

% The solution time in seconds is nearly the same as the number of function evaluations. This result indicates that the solver reused function values, and did not waste time by reevaluating the same point twice.
% For a more extensive example, see Objective and Constraints Using Common Function. For more information on using fcn2optimexpr, see Convert Nonlinear Function to Optimization Expression.
% Copyright 2018-2019 The MathWorks, Inc.