function  SSE = sumsqerr(x,data)

% SUMSQERR -- Summed squared error b/n user-supplied model and data.
%
% SSE = sumsqerr(x,data)
%
% SUMSQERR is a generic function that allows arbitrary user-supplied 
% models to be fitted to data via Matlab's FMINCON function.
% It is similar to CURVEDIFF but returns a scalar SSE rather than
% a vector of individual errors.
% It is always true that  sumsqerr(x,data) = sum(curvediff(x,data).^2)
%
% DATA must be a strucuture with the following five fields:
%  - model_name -- name of the function implementing your model
%  - model_data -- arbitrary structure passed to your function
%  - params     -- a structure containing all parameters of the model
%  - v2p_templ  -- a vector-to-param conversion template that defines the
%       interpretation of the elements of the vector X. See functions
%       VECTOR2PARAMS, PARAMS2VECTOR, and SAMPLE_TEMPLATE for details.
%  - target_vals -- a matrix (not necessarily vector) of the values the
%       model is trying to fit. FEVAL(model_name,model_data) should return
%       a matrix of the same shape.
%
% This is intended for use with PARAMSEARCH and FMINCON.
% Type 'edit curvediff' to see the exact algorithm.
%
% See also PARAMSEARCH, CURVEDIFF, FMINCON, LSQNONLIN, LOGL, SUMSQ.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.0 $  $Date: 2007-08-16 $
%
% Part of the utils toolbox version 1.1 for MATLAB version 5 and up.
% http://alexpetrov.com/softw/utils/
% Copyright (c) Alexander Petrov 1999-2006, http://alexpetrov.com
% Please read the LICENSE and NO WARRANTY statement in ../utils_license.m

params = vector2params(x,data.params,data.v2p_templ) ;

model_data = data.model_data ;
model_data.params = params ;

model_vals = feval(data.model_name,model_data) ;   % <-- main load

SSE = data.target_vals - model_vals ;
SSE = sum(SSE(:).^2) ;

%%% Return SSE
%%%%% End of file SUMSQERR.M
