function varargout = minimize_args(fn, length, varargin) %MINIMIZE_ARGS use Carl Rasmussen's MINIMIZE on multiple array variables % % [x1, x2, ..., fn_value, i] = optimize_args(fn, length, varargin) % % This calls Carl Rasmussen's minimize, but allows minimizing % functions with the following signature: % [f_value, df_dx1, ... df_dxK] = fn(x1, ..., xK) % fn's arguments can be nd-arrays, not just vectors. All the dirty wrapping and % unwrapping of parameters in and out of vectors is done for you. % % Inputs: % fn @fn Function to optimize % length 1x1 Number of fn evals (if +ve) / line searches (if -ve) % See Carl's code for more information % varargin arglist Initial conditions for variables % % Outputs: % varargout ?x? [opt_x1, opt_x2, ..., opt_xK, opt_fn_value, i] % (as in Carl's code, "i" is # fn evals or line searches) % Iain Murray, November 2007, July 2008 [wrap, unwrap] = arg_wrappers(varargin{:}); init = wrap(varargin{:}); min_fn = @(x) cost_grad_fn(x, fn, wrap, unwrap); [X, fX, i] = minimize(init, min_fn, length); minimum = unwrap(X); varargout = {minimum{:}, fX, i}; function [fx, dfx] = cost_grad_fn(x, fn, wrap, unwrap) args = unwrap(x); out = cell(length(args) + 1, 1); [out{:}] = fn(args{:}); fx = out{1}; dfx = wrap(out{2:end});