function  PARAMS = vector2params(x,old_params,template)

% VECTOR2PARAMS -- Converts a vector into a PARAMS structure.
%   
%   PARAMS = VECTOR2PARAMS(X,OLD_PARAMS,TEMPLATE)
%
%   It is convenient to pack model parameters into "params" structures.
%   The function minimization routines such as FMINCON, however, require
%   vector input.  PARAMS2VECTOR and VECTOR2PARAMS convert between the
%   two formats, guided by user-supplied templates.
%
%   X must be a vector. TEMPLATE must be a cell array of strings 
%   specifying the conversion. X and TEMPLATE must have the same shape.
%   OLD_PARAMS must be a parameter structure; it supplies values for
%   the fields not included in the vector.
% 
%   Each TEMPLATE string must have the form  'PARAMS.xyz = ... VAL .... ;'
%   That is, some field of a structure called PARAMS (in capital letters) 
%   is assigned a value depending on the variable VAL (in capital letters).
%   The elements of the input vector are copied to the variable VAL in
%   turn, and then the corresponding TEMPLATE string is executed using EVAL.
%   The TEMPLATE strings must have legal MATLAB syntax and end w/ semicolon.
%
%   Example:  Consider the template
%     template = {'PARAMS.alpha = VAL ;' , 'PARAMS.beta = VAL ;'}
%   Then the call  params = vector2params([1 2],old_params,template)  
%   produces a structure that is identical to OLD_PARAMS except that the
%   'alpha' field has value 1 and the 'beta' field has value 2.
%
%   Example:
%     params = default_params('your_model') ;
%     p2v_templ = sample_template('params2vector') ;
%     x0 = params2vector(params,p2v_templ) ;
%     optimal_x = fmincon('logL',x0,...) ;          % see LOGL
%     v2p_templ = sample_template('vector2params') ;
%     optimal_params = vector2params(optimal_x,params,v2p_templ) ;
%
%   See also PARAMS2VECTOR, SAMPLE_TEMPLATE, LOGL.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.0 $  $Date: 2000/06/07 15:30 $
%
% 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

if (any(size(x) ~= size(template)))
  error('X and TEMPLATE must have the same shape.') ;
end

PARAMS = old_params ;
VAL = NaN ;

for k = 1:length(template)
  VAL = x(k) ;
  eval(template{k}) ;
end

%% Return PARAMS
%%%%% End of file PARAMS2VECTOR.M
