function d = curvediff(x,data)

% CURVEDIFF -- Vector of differences b/n user-supplied model and data.
%
% d = curvediff(x,data)
%
% CURVEDIFF is a generic function that allows arbitrary user-supplied 
% models to be fitted to data via Matlab's LSQNONLIN function.
%
% 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.
%
% CURVEDIFF returns a column vector = target_vals(:) - model_vals(:)
% where model_vals = feval(model_name,model_data)
%
% This is intended for use with PARAMSEARCH and LSQNONLIN.
%
% Type 'edit curvediff' to see the exact algorithm.
%
% See also PARAMSEARCH, SUMSQERR, LSQNONLIN, LSQCURVEFIT, LOGL.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.0 $  $Date: 2007-08-15 $
%
% 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

d = data.target_vals(:) - model_vals(:) ;

%%% Return D
%%%%% End of file CURVEDIFF.M
