% Generate random problem data.
n = 1000;
A = randn(n);
A = .5*(A+A.');
% Create the problem structure.
manifold = spherefactory(n);
problem.M = manifold;
% Define the problem cost function and its Euclidean gradient.
problem.cost = @mycost;
problem.egrad = @myegrad; % notice the 'e' in 'egrad' for Euclidean
% Numerically check gradient consistency (optional).
checkgradient(problem);
% Solve.
[x, xcost, info, options] = trustregions(problem);
% Display some statistics.
figure;
semilogy([info.iter], [info.gradnorm], '.-');
xlabel('Iteration number');
ylabel('Norm of the gradient of f');
function [f, store] = mycost(x, store)
if ~isfield(store, 'Ax')
store.Ax = A*x; % The store memory is associated to a specific x
end
Ax = store.Ax;
f = -x'*Ax; % No need to cache f: cost values are cached 'under the hood'
end
function [g, store] = myegrad(x, store)
% This could be placed in a separate function
% to avoid code duplication.
if ~isfield(store, 'Ax')
store.Ax = A*x;
end
Ax = store.Ax;
% Euclidean gradient; this is also cached 'under the hood'.
g = -2*Ax;
end